Skip to content

Commit 94614cf

Browse files
committed
feat: add number of islands solution
1 parent 69fc090 commit 94614cf

File tree

4 files changed

+201
-14
lines changed

4 files changed

+201
-14
lines changed

README.md

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,18 @@
1919

2020
## Medium
2121

22-
| # | Problem | Solution | Time | Space | Tag |
23-
| --- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ---------- | ------------------------------------------------------------------------------- |
24-
| 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 |
25-
| 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 |
26-
| 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 |
27-
| 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 |
28-
| 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 |
29-
| 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 |
30-
| 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 |
31-
| 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 |
32-
| 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 |
33-
| 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 |
34-
| 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 |
35-
| 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 |
22+
| # | Problem | Solution | Time | Space | Tag |
23+
| --- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ----------- | ------------------------------------------------------------------------------- |
24+
| 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 |
25+
| 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 |
26+
| 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 |
27+
| 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 |
28+
| 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 |
29+
| 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 |
30+
| 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 |
31+
| 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 |
32+
| 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 |
33+
| 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 |
34+
| 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 |
35+
| 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 |
36+
| 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 |
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# [Number of Islands](https://leetcode.com/problems/number-of-islands/)
2+
3+
## Description
4+
5+
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.
6+
7+
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.
8+
9+
**Example 1:**
10+
11+
```
12+
Input: grid = [
13+
["1","1","1","1","0"],
14+
["1","1","0","1","0"],
15+
["1","1","0","0","0"],
16+
["0","0","0","0","0"]
17+
]
18+
Output: 1
19+
```
20+
21+
**Example 2:**
22+
23+
```
24+
Input: grid = [
25+
["1","1","0","0","0"],
26+
["1","1","0","0","0"],
27+
["0","0","1","0","0"],
28+
["0","0","0","1","1"]
29+
]
30+
Output: 3
31+
```
32+
33+
## Solution
34+
35+
```typescript
36+
function numIslands(grid: string[][]): number {
37+
if (!grid || grid.length === 0) {
38+
return 0;
39+
}
40+
41+
const numRows = grid.length;
42+
const numCols = grid[0].length;
43+
let count = 0;
44+
45+
const directions = [
46+
[1, 0],
47+
[-1, 0],
48+
[0, 1],
49+
[0, -1],
50+
];
51+
52+
function bfs(row: number, col: number) {
53+
const queue: [number, number][] = [[row, col]];
54+
// Mark the current cell as visited
55+
grid[row][col] = "0";
56+
57+
while (queue.length > 0) {
58+
const [currentRow, currentCol] = queue.shift()!;
59+
60+
for (const [dr, dc] of directions) {
61+
const newRow = currentRow + dr;
62+
const newCol = currentCol + dc;
63+
64+
if (
65+
newRow >= 0 &&
66+
newRow < numRows &&
67+
newCol >= 0 &&
68+
newCol < numCols &&
69+
grid[newRow][newCol] === "1"
70+
) {
71+
queue.push([newRow, newCol]);
72+
// Mark the adjacent cell as visited
73+
grid[newRow][newCol] = "0";
74+
}
75+
}
76+
}
77+
}
78+
79+
for (let row = 0; row < numRows; row++) {
80+
for (let col = 0; col < numCols; col++) {
81+
if (grid[row][col] === "1") {
82+
count++;
83+
bfs(row, col);
84+
}
85+
}
86+
}
87+
88+
return count;
89+
}
90+
```
91+
92+
## Complexity Analysis
93+
94+
- Time complexity: _O(m \* n)_
95+
- Space complexity: _O(m \* n)_
96+
97+
Where M is the number of rows and N is the number of columns in the grid.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { numIslands } from "./numIslands";
2+
3+
describe("Number of Islands", () => {
4+
it("should return the correct number of islands", () => {
5+
const grid1 = [
6+
["1", "1", "0", "0", "0"],
7+
["1", "1", "0", "0", "0"],
8+
["0", "0", "1", "0", "0"],
9+
["0", "0", "0", "1", "1"],
10+
];
11+
expect(numIslands(grid1)).toBe(3);
12+
13+
const grid2 = [
14+
["1", "1", "1", "1", "0"],
15+
["1", "1", "0", "1", "0"],
16+
["1", "1", "0", "0", "0"],
17+
["0", "0", "0", "0", "0"],
18+
];
19+
expect(numIslands(grid2)).toBe(1);
20+
});
21+
22+
it("should return 0 for an empty grid", () => {
23+
const emptyGrid: string[][] = [];
24+
expect(numIslands(emptyGrid)).toBe(0);
25+
});
26+
27+
it("should return 0 when there are no islands", () => {
28+
const noIslandsGrid = [
29+
["0", "0", "0"],
30+
["0", "0", "0"],
31+
["0", "0", "0"],
32+
];
33+
expect(numIslands(noIslandsGrid)).toBe(0);
34+
});
35+
});
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
export function numIslands(grid: string[][]): number {
2+
if (!grid || grid.length === 0) {
3+
return 0;
4+
}
5+
6+
const numRows = grid.length;
7+
const numCols = grid[0].length;
8+
let count = 0;
9+
10+
const directions = [
11+
[1, 0],
12+
[-1, 0],
13+
[0, 1],
14+
[0, -1],
15+
];
16+
17+
function bfs(row: number, col: number) {
18+
const queue: [number, number][] = [[row, col]];
19+
// Mark the current cell as visited
20+
grid[row][col] = "0";
21+
22+
while (queue.length > 0) {
23+
const [currentRow, currentCol] = queue.shift()!;
24+
25+
for (const [dr, dc] of directions) {
26+
const newRow = currentRow + dr;
27+
const newCol = currentCol + dc;
28+
29+
if (
30+
newRow >= 0 &&
31+
newRow < numRows &&
32+
newCol >= 0 &&
33+
newCol < numCols &&
34+
grid[newRow][newCol] === "1"
35+
) {
36+
queue.push([newRow, newCol]);
37+
// Mark the adjacent cell as visited
38+
grid[newRow][newCol] = "0";
39+
}
40+
}
41+
}
42+
}
43+
44+
for (let row = 0; row < numRows; row++) {
45+
for (let col = 0; col < numCols; col++) {
46+
if (grid[row][col] === "1") {
47+
count++;
48+
bfs(row, col);
49+
}
50+
}
51+
}
52+
53+
return count;
54+
}

0 commit comments

Comments
 (0)