Skip to content

Commit

Permalink
feat: add number of islands solution
Browse files Browse the repository at this point in the history
  • Loading branch information
sandrig committed Aug 10, 2023
1 parent 69fc090 commit 94614cf
Show file tree
Hide file tree
Showing 4 changed files with 201 additions and 14 deletions.
29 changes: 15 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,18 @@

## Medium

| # | Problem | Solution | Time | Space | Tag |
| --- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ---------- | ------------------------------------------------------------------------------- |
| 1 | [String Compression](https://leetcode.com/problems/string-compression/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/stringCompression/README.md) | _O(n)_ | _O(n)_ | Two Pointers, String |
| 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/addTwoNumbers/README.md) | _O(n)_ | _O(1)_ | Linked List, Math, Recursion |
| 3 | [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/insertDeleteGetRandom/README.md) | _O(1)_ | _O(n)_ | Array, Hash Table, Math, Design, Randomized |
| 4 | [Group Anagrams](https://leetcode.com/problems/group-anagrams/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/groupAnagrams/README.md) | _O(n\*k log(k))_ | _O(n\*K)_ | Array, Hash Table, String, Sorting |
| 5 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/subarraySumEqualsK/README.md) | _O(n)_ | _O(n)_ | Array, Hash Table, Prefix Sum |
| 6 | [Merge Intervals](https://leetcode.com/problems/merge-intervals/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/mergeIntervals/README.md) | _O(n log n)_ | _O(n)_ | Array, Sorting |
| 7 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/topkFrequentWords/README.md) | _O(n log n)_ | _O(n + k)_ | Hash Table, String, Trie, Sorting, Heap (Priority Queue), Bucket Sort, Counting |
| 8 | [Longest Subarray of 1's After Deleting One Element](https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/longestSubarrayof1sAfterDeletingOneElement/README.md) | _O(n)_ | _O(1)_ | Array, Dynamic Programming, Sliding Window |
| 9 | [Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/maximizeDistanceToClosestPerson/README.md) | _O(n)_ | _O(1)_ | Array |
| 10 | [Find the Prefix Common Array of Two Arrays](https://leetcode.com/problems/find-the-prefix-common-array-of-two-arrays/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/findThePrefixCommonArrayOfTwoArrays/README.md) | _O(n)_ | _O(n)_ | Array, Hash Table |
| 11 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/findAllAnagramsInaString/README.md) | _O(n)_ | _O(1)_ | Hash Table, String, Sliding Window |
| 12 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/binaryTreeLevelOrderTraversal/README.md) | _O(n)_ | _O(n)_ | Tree, Breadth-First, Search, Binary Tree |
| # | Problem | Solution | Time | Space | Tag |
| --- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ----------- | ------------------------------------------------------------------------------- |
| 1 | [String Compression](https://leetcode.com/problems/string-compression/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/stringCompression/README.md) | _O(n)_ | _O(n)_ | Two Pointers, String |
| 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/addTwoNumbers/README.md) | _O(n)_ | _O(1)_ | Linked List, Math, Recursion |
| 3 | [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/insertDeleteGetRandom/README.md) | _O(1)_ | _O(n)_ | Array, Hash Table, Math, Design, Randomized |
| 4 | [Group Anagrams](https://leetcode.com/problems/group-anagrams/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/groupAnagrams/README.md) | _O(n\*k log(k))_ | _O(n\*K)_ | Array, Hash Table, String, Sorting |
| 5 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/subarraySumEqualsK/README.md) | _O(n)_ | _O(n)_ | Array, Hash Table, Prefix Sum |
| 6 | [Merge Intervals](https://leetcode.com/problems/merge-intervals/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/mergeIntervals/README.md) | _O(n log n)_ | _O(n)_ | Array, Sorting |
| 7 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/topkFrequentWords/README.md) | _O(n log n)_ | _O(n + k)_ | Hash Table, String, Trie, Sorting, Heap (Priority Queue), Bucket Sort, Counting |
| 8 | [Longest Subarray of 1's After Deleting One Element](https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/longestSubarrayof1sAfterDeletingOneElement/README.md) | _O(n)_ | _O(1)_ | Array, Dynamic Programming, Sliding Window |
| 9 | [Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/maximizeDistanceToClosestPerson/README.md) | _O(n)_ | _O(1)_ | Array |
| 10 | [Find the Prefix Common Array of Two Arrays](https://leetcode.com/problems/find-the-prefix-common-array-of-two-arrays/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/findThePrefixCommonArrayOfTwoArrays/README.md) | _O(n)_ | _O(n)_ | Array, Hash Table |
| 11 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/findAllAnagramsInaString/README.md) | _O(n)_ | _O(1)_ | Hash Table, String, Sliding Window |
| 12 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/binaryTreeLevelOrderTraversal/README.md) | _O(n)_ | _O(n)_ | Tree, Breadth-First, Search, Binary Tree |
| 13 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [TypeScript](https://github.com/sandrig/leetcode/blob/master/typescript/src/numberOfIslands/README.md) | _O(m \* n)_ | _O(m \* n)_ | Array, Depth-First, Search Breadth-First Search, Union Find, Matrix |
97 changes: 97 additions & 0 deletions typescript/src/numberOfIslands/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# [Number of Islands](https://leetcode.com/problems/number-of-islands/)

## Description

Given an **m x n** 2D binary grid **grid** which represents a map of **'1'**s (land) and **'0'**s (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

**Example 1:**

```
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
```

**Example 2:**

```
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
```

## Solution

```typescript
function numIslands(grid: string[][]): number {
if (!grid || grid.length === 0) {
return 0;
}

const numRows = grid.length;
const numCols = grid[0].length;
let count = 0;

const directions = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];

function bfs(row: number, col: number) {
const queue: [number, number][] = [[row, col]];
// Mark the current cell as visited
grid[row][col] = "0";

while (queue.length > 0) {
const [currentRow, currentCol] = queue.shift()!;

for (const [dr, dc] of directions) {
const newRow = currentRow + dr;
const newCol = currentCol + dc;

if (
newRow >= 0 &&
newRow < numRows &&
newCol >= 0 &&
newCol < numCols &&
grid[newRow][newCol] === "1"
) {
queue.push([newRow, newCol]);
// Mark the adjacent cell as visited
grid[newRow][newCol] = "0";
}
}
}
}

for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
if (grid[row][col] === "1") {
count++;
bfs(row, col);
}
}
}

return count;
}
```

## Complexity Analysis

- Time complexity: _O(m \* n)_
- Space complexity: _O(m \* n)_

Where M is the number of rows and N is the number of columns in the grid.
35 changes: 35 additions & 0 deletions typescript/src/numberOfIslands/numIslands.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { numIslands } from "./numIslands";

describe("Number of Islands", () => {
it("should return the correct number of islands", () => {
const grid1 = [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"],
];
expect(numIslands(grid1)).toBe(3);

const grid2 = [
["1", "1", "1", "1", "0"],
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"],
];
expect(numIslands(grid2)).toBe(1);
});

it("should return 0 for an empty grid", () => {
const emptyGrid: string[][] = [];
expect(numIslands(emptyGrid)).toBe(0);
});

it("should return 0 when there are no islands", () => {
const noIslandsGrid = [
["0", "0", "0"],
["0", "0", "0"],
["0", "0", "0"],
];
expect(numIslands(noIslandsGrid)).toBe(0);
});
});
54 changes: 54 additions & 0 deletions typescript/src/numberOfIslands/numIslands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
export function numIslands(grid: string[][]): number {
if (!grid || grid.length === 0) {
return 0;
}

const numRows = grid.length;
const numCols = grid[0].length;
let count = 0;

const directions = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];

function bfs(row: number, col: number) {
const queue: [number, number][] = [[row, col]];
// Mark the current cell as visited
grid[row][col] = "0";

while (queue.length > 0) {
const [currentRow, currentCol] = queue.shift()!;

for (const [dr, dc] of directions) {
const newRow = currentRow + dr;
const newCol = currentCol + dc;

if (
newRow >= 0 &&
newRow < numRows &&
newCol >= 0 &&
newCol < numCols &&
grid[newRow][newCol] === "1"
) {
queue.push([newRow, newCol]);
// Mark the adjacent cell as visited
grid[newRow][newCol] = "0";
}
}
}
}

for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
if (grid[row][col] === "1") {
count++;
bfs(row, col);
}
}
}

return count;
}

0 comments on commit 94614cf

Please sign in to comment.