1568. Minimum Number of Days to Disconnect Island
Problem Description
You have a binary grid where 1
represents land and 0
represents water. An island is formed by connecting adjacent land cells horizontally or vertically (4-directionally connected). The grid is considered "connected" if it contains exactly one island, and "disconnected" if it has zero islands or more than one island.
Each day, you can change one land cell (1
) into a water cell (0
). Your goal is to find the minimum number of days needed to disconnect the grid.
The solution works by first checking if the grid is already disconnected (has 0 or 2+ islands). If so, it returns 0
days. Then it tries removing each land cell one by one to see if that disconnects the grid - if any single removal works, it returns 1
day. Otherwise, it returns 2
days, since removing at most 2 cells is always sufficient to disconnect any connected grid.
The count
function uses depth-first search (DFS) to count the number of islands. It marks visited land cells as 2
during traversal, counts each connected component as one island, then restores the original values afterward. This allows checking how many islands exist after each potential cell removal.
The key insight is that any connected grid can be disconnected in at most 2 days - either the grid is already disconnected (0 days), can be disconnected by removing one strategic cell (1 day), or requires removing two cells (2 days).
Flowchart Walkthrough
First, let's pin down the algorithm using the Flowchart. Here's a step-by-step walkthrough:
Is it a graph?
- Yes: The grid represents a graph where each cell is a node, and adjacent land cells (horizontally or vertically) form edges between nodes. Islands are essentially connected components in this graph.
Is it a tree?
- No: The problem involves a grid that can have cycles (land cells forming loops) and multiple disconnected components. It's not a tree structure.
Is the problem related to directed acyclic graphs?
- No: The grid represents an undirected graph where connections between adjacent land cells are bidirectional.
Is the problem related to shortest paths?
- No: We're not finding shortest paths between nodes. Instead, we need to count connected components (islands) and determine connectivity.
Does the problem involve connectivity?
- Yes: The core of the problem is about connectivity - we need to determine if the grid has exactly one connected component (island) and find the minimum removals to disconnect it.
Does the problem have small constraints?
- Yes: While not explicitly stated, the problem involves trying all possible single cell removals (at most mΓn attempts) and potentially checking pairs, which is feasible for reasonable grid sizes.
Brute force / Backtracking?
- Yes: We use a brute force approach with DFS - first checking if already disconnected, then trying each cell removal one by one, which involves DFS to count islands after each removal.
Conclusion: The flowchart leads us to use DFS with a brute force approach. DFS is used to count the number of islands (connected components) in the grid, and we systematically try removing cells to find the minimum days needed to disconnect the grid.
Intuition
The key insight starts with understanding what makes a grid "disconnected" - it needs to have either zero islands or more than one island. If we already have this condition, we need 0
days.
For a connected grid (exactly one island), we need to find critical points that, when removed, would split the island. Think of it like finding the weakest link in a chain - some cells act as bridges connecting different parts of the island.
Why can we always disconnect in at most 2
days? Consider any connected island - even in the worst case where it's a solid rectangle, we can always find a corner cell and its adjacent cell. Removing these two cells will either isolate the corner or create a disconnection. This gives us our upper bound.
The approach becomes clear:
- First check if we need
0
days (already disconnected) - Then try removing each land cell one at a time - if any single removal disconnects the grid, we need
1
day - If no single cell removal works, we know
2
days is sufficient
The DFS counting mechanism is elegant - we temporarily mark visited cells as 2
during traversal to avoid revisiting them, count each connected component as one island, then restore the original values. This allows us to non-destructively test each scenario.
The brute force nature (trying each cell) might seem inefficient, but it's actually optimal here because determining the minimum cuts in a graph is inherently complex, and with the small constraint that the answer is at most 2
, checking all single-cell removals is practical and guarantees finding the minimum.
Learn more about Depth-First Search and Breadth-First Search patterns.
Solution Approach
The solution implements a brute force approach with DFS to count connected components. Let's walk through the implementation:
Main Function (minDays
):
-
Initial Check: First, we call
self.count(grid)
to determine if the grid is already disconnected. If the number of islands is not exactly 1, return0
days. -
Try Single Cell Removal: Iterate through each cell in the grid. For each land cell (
grid[i][j] == 1
):- Temporarily change it to water:
grid[i][j] = 0
- Count the islands again using
self.count(grid)
- If the count is not 1 (either 0 or 2+ islands), we found a solution with
1
day - Restore the cell:
grid[i][j] = 1
for the next iteration
- Temporarily change it to water:
-
Default Case: If no single cell removal disconnects the grid, return
2
days.
Island Counting Function (count
):
The counting function uses DFS with a clever marking technique:
-
DFS Helper: The nested
dfs(i, j)
function:- Marks the current cell as
2
(visited) - Explores all 4 directions:
[[0, -1], [0, 1], [1, 0], [-1, 0]]
- Recursively visits adjacent land cells that haven't been visited
- Marks the current cell as
-
Counting Process:
- Initialize counter
cnt = 0
- Iterate through the entire grid
- When finding an unvisited land cell (
grid[i][j] == 1
), start a DFS from there - Increment the counter for each new island found
- Initialize counter
-
Restoration: After counting, restore all cells marked as
2
back to1
:for i in range(m): for j in range(n): if grid[i][j] == 2: grid[i][j] = 1
Time Complexity: O(mΒ² Γ nΒ²)
where m and n are grid dimensions - we potentially try removing each cell (O(m Γ n)
) and for each removal, we run DFS to count islands (O(m Γ n)
).
Space Complexity: O(m Γ n)
for the recursion stack in worst case when DFS traverses all cells.
The elegance lies in the temporary marking strategy - using 2
to mark visited cells allows us to count islands without creating a separate visited array, and we can easily restore the grid afterward for the next test.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through a small example to illustrate the solution approach.
Consider this 2Γ3 grid:
1 1 1 1 0 1
Step 1: Check if already disconnected
- Run DFS from position (0,0)
- DFS visits: (0,0) β (0,1) β (0,2) β (1,2) β (1,0)
- All land cells are reachable from one starting point
- Island count = 1 (connected), so we need to proceed
Step 2: Try removing each land cell one by one
Try removing (0,0):
0 1 1 (temporarily set grid[0][0] = 0) 1 0 1
- Count islands: Start DFS from (0,1), visits (0,1) β (0,2) β (1,2)
- Another DFS starts from (1,0), visits only (1,0)
- Island count = 2 β Grid is disconnected! Return 1 day
Let's verify another removal to understand why some cells work and others don't:
Try removing (0,1):
1 0 1 (temporarily set grid[0][1] = 0) 1 0 1
- Count islands: DFS from (0,0) visits only (0,0)
- DFS from (0,2) visits (0,2) β (1,2)
- DFS from (1,0) visits only (1,0)
- Island count = 3 β This also disconnects the grid
Try removing (1,2):
1 1 1 (temporarily set grid[1][2] = 0) 1 0 0
- Count islands: DFS from (0,0) visits (0,0) β (0,1) β (0,2) β (1,0)
- Island count = 1 β Still connected, this cell isn't critical
Result: Since removing cell (0,0) disconnects the grid, the answer is 1 day.
The DFS marking process during counting:
- When visiting a cell, mark it as
2
- After exploring all connected cells, we have one island marked with
2
s - Restore all
2
s back to1
s before the next test - This avoids creating a separate visited array and keeps the grid intact for subsequent checks
Solution Implementation
1class Solution:
2 def minDays(self, grid: List[List[int]]) -> int:
3 """
4 Find minimum number of days to disconnect the island.
5 Each day we can change one land cell (1) to water (0).
6 Returns 0 if already disconnected, 1 if one removal suffices, otherwise 2.
7 """
8 # Check if grid is already disconnected
9 if self.count_islands(grid) != 1:
10 return 0
11
12 rows, cols = len(grid), len(grid[0])
13
14 # Try removing each land cell one by one
15 for row in range(rows):
16 for col in range(cols):
17 if grid[row][col] == 1:
18 # Temporarily remove this land cell
19 grid[row][col] = 0
20
21 # Check if removal disconnects the island
22 if self.count_islands(grid) != 1:
23 return 1
24
25 # Restore the land cell
26 grid[row][col] = 1
27
28 # If no single removal works, we need at most 2 removals
29 # (This is always possible for any connected island)
30 return 2
31
32 def count_islands(self, grid: List[List[int]]) -> int:
33 """
34 Count the number of disconnected islands in the grid.
35 Uses DFS to mark visited cells.
36 """
37 def depth_first_search(row: int, col: int) -> None:
38 """
39 DFS helper to mark all connected land cells starting from (row, col).
40 Marks visited cells as 2 temporarily.
41 """
42 # Mark current cell as visited
43 grid[row][col] = 2
44
45 # Check all 4 adjacent cells (up, down, left, right)
46 directions = [[0, -1], [0, 1], [1, 0], [-1, 0]]
47 for delta_row, delta_col in directions:
48 new_row, new_col = row + delta_row, col + delta_col
49
50 # If adjacent cell is valid and is unvisited land
51 if (0 <= new_row < rows and
52 0 <= new_col < cols and
53 grid[new_row][new_col] == 1):
54 depth_first_search(new_row, new_col)
55
56 rows, cols = len(grid), len(grid[0])
57 island_count = 0
58
59 # Find and count all islands
60 for row in range(rows):
61 for col in range(cols):
62 if grid[row][col] == 1:
63 # Found a new island, explore it completely
64 depth_first_search(row, col)
65 island_count += 1
66
67 # Restore all visited cells (marked as 2) back to land (1)
68 for row in range(rows):
69 for col in range(cols):
70 if grid[row][col] == 2:
71 grid[row][col] = 1
72
73 return island_count
74
1class Solution {
2 // Direction vectors for exploring 4 adjacent cells (up, right, down, left)
3 private static final int[] DIRECTIONS = new int[] {-1, 0, 1, 0, -1};
4 private int[][] grid;
5 private int rows;
6 private int cols;
7
8 /**
9 * Finds the minimum number of days to disconnect the island.
10 * An island is disconnected when it's split into 2+ islands or no islands remain.
11 *
12 * @param grid 2D binary grid where 1 represents land and 0 represents water
13 * @return minimum days needed to disconnect the island (0, 1, or 2)
14 */
15 public int minDays(int[][] grid) {
16 this.grid = grid;
17 this.rows = grid.length;
18 this.cols = grid[0].length;
19
20 // Check if grid is already disconnected (not exactly 1 island)
21 if (countIslands() != 1) {
22 return 0;
23 }
24
25 // Try removing each land cell one at a time
26 for (int row = 0; row < rows; row++) {
27 for (int col = 0; col < cols; col++) {
28 if (grid[row][col] == 1) {
29 // Temporarily remove this land cell
30 grid[row][col] = 0;
31
32 // Check if removing this cell disconnects the island
33 if (countIslands() != 1) {
34 return 1;
35 }
36
37 // Restore the land cell
38 grid[row][col] = 1;
39 }
40 }
41 }
42
43 // If removing any single cell doesn't work, we need at most 2 days
44 // (This is always possible for any connected island with 2+ cells)
45 return 2;
46 }
47
48 /**
49 * Counts the number of islands in the current grid state.
50 * Uses DFS to mark connected components.
51 *
52 * @return number of distinct islands
53 */
54 private int countIslands() {
55 int islandCount = 0;
56
57 // Find and mark each island using DFS
58 for (int row = 0; row < rows; row++) {
59 for (int col = 0; col < cols; col++) {
60 if (grid[row][col] == 1) {
61 // Found an unvisited land cell, explore the entire island
62 depthFirstSearch(row, col);
63 islandCount++;
64 }
65 }
66 }
67
68 // Restore all visited cells (marked as 2) back to land (1)
69 for (int row = 0; row < rows; row++) {
70 for (int col = 0; col < cols; col++) {
71 if (grid[row][col] == 2) {
72 grid[row][col] = 1;
73 }
74 }
75 }
76
77 return islandCount;
78 }
79
80 /**
81 * Performs DFS to mark all connected land cells starting from (row, col).
82 * Marks visited cells with value 2 to avoid revisiting.
83 *
84 * @param row current row index
85 * @param col current column index
86 */
87 private void depthFirstSearch(int row, int col) {
88 // Mark current cell as visited
89 grid[row][col] = 2;
90
91 // Explore all 4 adjacent directions
92 for (int direction = 0; direction < 4; direction++) {
93 int nextRow = row + DIRECTIONS[direction];
94 int nextCol = col + DIRECTIONS[direction + 1];
95
96 // Check if the adjacent cell is valid and is unvisited land
97 if (nextRow >= 0 && nextRow < rows &&
98 nextCol >= 0 && nextCol < cols &&
99 grid[nextRow][nextCol] == 1) {
100 depthFirstSearch(nextRow, nextCol);
101 }
102 }
103 }
104}
105
1class Solution {
2public:
3 // Direction vectors for exploring 4 adjacent cells (up, right, down, left)
4 const vector<int> directions = {-1, 0, 1, 0, -1};
5 int rows, cols;
6
7 /**
8 * Find minimum number of days to disconnect the island
9 * @param grid - 2D grid where 1 represents land and 0 represents water
10 * @return Minimum number of days (cells to remove) to disconnect the island
11 */
12 int minDays(vector<vector<int>>& grid) {
13 rows = grid.size();
14 cols = grid[0].size();
15
16 // Check if grid is already disconnected (not exactly 1 island)
17 if (countIslands(grid) != 1) {
18 return 0;
19 }
20
21 // Try removing each land cell one by one
22 for (int row = 0; row < rows; ++row) {
23 for (int col = 0; col < cols; ++col) {
24 if (grid[row][col] == 1) {
25 // Temporarily remove this land cell
26 grid[row][col] = 0;
27
28 // Check if removing this cell disconnects the island
29 if (countIslands(grid) != 1) {
30 return 1;
31 }
32
33 // Restore the land cell
34 grid[row][col] = 1;
35 }
36 }
37 }
38
39 // If removing any single cell doesn't work, we need at most 2 days
40 return 2;
41 }
42
43 /**
44 * Count the number of islands in the grid
45 * @param grid - 2D grid to analyze
46 * @return Number of distinct islands
47 */
48 int countIslands(vector<vector<int>>& grid) {
49 int islandCount = 0;
50
51 // Find all islands using DFS
52 for (int row = 0; row < rows; ++row) {
53 for (int col = 0; col < cols; ++col) {
54 if (grid[row][col] == 1) {
55 // Found unvisited land, start DFS to mark entire island
56 dfsMarkIsland(row, col, grid);
57 ++islandCount;
58 }
59 }
60 }
61
62 // Restore the grid: change all visited cells (marked as 2) back to 1
63 for (int row = 0; row < rows; ++row) {
64 for (int col = 0; col < cols; ++col) {
65 if (grid[row][col] == 2) {
66 grid[row][col] = 1;
67 }
68 }
69 }
70
71 return islandCount;
72 }
73
74 /**
75 * Depth-first search to mark all connected land cells of an island
76 * @param row - Starting row position
77 * @param col - Starting column position
78 * @param grid - 2D grid being explored
79 */
80 void dfsMarkIsland(int row, int col, vector<vector<int>>& grid) {
81 // Mark current cell as visited (using value 2)
82 grid[row][col] = 2;
83
84 // Explore all 4 adjacent directions
85 for (int dir = 0; dir < 4; ++dir) {
86 int newRow = row + directions[dir];
87 int newCol = col + directions[dir + 1];
88
89 // Check if the adjacent cell is valid and is unvisited land
90 if (newRow >= 0 && newRow < rows &&
91 newCol >= 0 && newCol < cols &&
92 grid[newRow][newCol] == 1) {
93 dfsMarkIsland(newRow, newCol, grid);
94 }
95 }
96 }
97};
98
1/**
2 * Finds the minimum number of days to disconnect an island in a grid.
3 * An island is a group of 1's connected horizontally or vertically.
4 * Each day, you can change exactly one land cell (1) to water (0).
5 * @param grid - 2D array where 1 represents land and 0 represents water
6 * @returns Minimum number of days to disconnect the island
7 */
8function minDays(grid: number[][]): number {
9 const rows: number = grid.length;
10 const cols: number = grid[0].length;
11
12 /**
13 * Performs depth-first search to mark all connected land cells as visited.
14 * Marks visited cells with value 2 to distinguish from unvisited cells.
15 * @param row - Current row index
16 * @param col - Current column index
17 */
18 const markConnectedLand = (row: number, col: number): void => {
19 // Check boundaries and if cell is water (0) or already visited (2)
20 if (row < 0 || row >= rows || col < 0 || col >= cols ||
21 grid[row][col] === 0 || grid[row][col] === 2) {
22 return;
23 }
24
25 // Mark current cell as visited
26 grid[row][col] = 2;
27
28 // Direction vectors for exploring 4 adjacent cells (up, right, down, left)
29 const directions: number[] = [-1, 0, 1, 0, -1];
30
31 // Explore all 4 adjacent cells
32 for (let dirIndex = 0; dirIndex < 4; dirIndex++) {
33 const nextRow: number = row + directions[dirIndex];
34 const nextCol: number = col + directions[dirIndex + 1];
35 markConnectedLand(nextRow, nextCol);
36 }
37 };
38
39 /**
40 * Counts the number of islands in the grid.
41 * An island is a connected component of land cells.
42 * @returns Number of islands found
43 */
44 const countIslands = (): number => {
45 let islandCount: number = 0;
46
47 // Find and count all islands
48 for (let row = 0; row < rows; row++) {
49 for (let col = 0; col < cols; col++) {
50 if (grid[row][col] === 1) {
51 // Found an unvisited land cell, start DFS to mark entire island
52 markConnectedLand(row, col);
53 islandCount++;
54 }
55 }
56 }
57
58 // Restore all visited cells (2) back to land cells (1)
59 for (let row = 0; row < rows; row++) {
60 for (let col = 0; col < cols; col++) {
61 if (grid[row][col] === 2) {
62 grid[row][col] = 1;
63 }
64 }
65 }
66
67 return islandCount;
68 };
69
70 // Check if grid is already disconnected (0 or more than 1 island)
71 if (countIslands() !== 1) {
72 return 0;
73 }
74
75 // Try removing each land cell one by one
76 for (let row = 0; row < rows; row++) {
77 for (let col = 0; col < cols; col++) {
78 if (grid[row][col] === 1) {
79 // Temporarily remove this land cell
80 grid[row][col] = 0;
81
82 // Check if removing this cell disconnects the island
83 if (countIslands() !== 1) {
84 return 1;
85 }
86
87 // Restore the land cell
88 grid[row][col] = 1;
89 }
90 }
91 }
92
93 // If no single cell removal disconnects the island, we need 2 days
94 return 2;
95}
96
Time and Space Complexity
Time Complexity: O(mΒ² Γ nΒ²)
where m
is the number of rows and n
is the number of columns in the grid.
- The initial call to
count(grid)
takesO(m Γ n)
time to perform DFS and count islands - The main loop iterates through all
m Γ n
cells - For each cell with value 1 (worst case all cells), we:
- Set the cell to 0:
O(1)
- Call
count(grid)
:O(m Γ n)
for DFS traversal - Reset the cell to 1:
O(1)
- Set the cell to 0:
- In the worst case where all cells are 1, we perform
O(m Γ n)
iterations, each callingcount()
which takesO(m Γ n)
time - Total:
O(m Γ n) Γ O(m Γ n) = O(mΒ² Γ nΒ²)
Space Complexity: O(m Γ n)
- The recursive DFS in the
count()
function can go as deep as the total number of land cells in the worst case (when all cells form a single connected component in a snake-like pattern) - Maximum recursion depth:
O(m Γ n)
for the call stack - No additional data structures are used besides the recursion stack
- The grid is modified in-place during DFS but restored after each count operation
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Forgetting to Restore Modified Grid State
One of the most common mistakes is modifying the grid during island counting or cell removal testing without properly restoring it. This leads to incorrect results in subsequent iterations.
Pitfall Example:
def count_islands_wrong(self, grid):
def dfs(i, j):
grid[i][j] = 2 # Mark as visited
# ... DFS logic ...
# Count islands...
# FORGOT to restore cells marked as 2 back to 1!
return island_count
Solution: Always restore the grid after modifications. The correct approach uses a restoration loop:
# After counting islands
for i in range(rows):
for j in range(cols):
if grid[i][j] == 2:
grid[i][j] = 1
2. Incorrect Boundary Checking in DFS
Another frequent error is improper boundary validation when exploring adjacent cells, leading to index out of bounds errors or missed cells.
Pitfall Example:
def dfs(i, j):
grid[i][j] = 2
for di, dj in directions:
ni, nj = i + di, j + dj
# Wrong: using OR instead of AND for boundary check
if 0 <= ni < rows or 0 <= nj < cols: # Should be AND!
if grid[ni][nj] == 1:
dfs(ni, nj)
Solution: Use AND operator for boundary checks to ensure both row and column indices are valid:
if (0 <= new_row < rows and 0 <= new_col < cols and grid[new_row][new_col] == 1): dfs(new_row, new_col)
3. Assuming Maximum Days is Always 2
While the mathematical proof shows that any connected grid can be disconnected in at most 2 days, directly returning 2 without checking single-cell removals would miss optimal solutions.
Pitfall Example:
def minDays_wrong(self, grid):
if self.count_islands(grid) != 1:
return 0
# Wrong: Skip checking 1-day solutions
return 2 # Missing the check for 1-day disconnection!
Solution: Always check if removing a single cell can disconnect the grid before defaulting to 2:
# Try each cell removal first
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
grid[i][j] = 0
if self.count_islands(grid) != 1:
return 1
grid[i][j] = 1
# Only return 2 if no single removal works
return 2
4. Not Handling Edge Cases Properly
Failing to consider grids that are already disconnected (0 islands or multiple islands) at the start.
Pitfall Example:
def minDays_wrong(self, grid):
# Wrong: Assumes grid always has exactly 1 island initially
for i in range(rows):
for j in range(cols):
# ... try removing cells ...
Solution: Always check the initial state first:
if self.count_islands(grid) != 1: return 0 # Already disconnected
5. Using a Separate Visited Array Unnecessarily
Creating a separate 2D visited array increases space complexity and code complexity when the grid itself can serve as the visited tracker.
Pitfall Example:
def count_islands_inefficient(self, grid):
visited = [[False] * cols for _ in range(rows)] # Extra O(m*n) space
def dfs(i, j):
visited[i][j] = True
# ... more complex logic to check both grid and visited ...
Solution: Use the grid itself by temporarily marking visited cells with a different value (like 2), then restore them afterward. This maintains O(1) extra space beyond the recursion stack.
What's the output of running the following function using input 56
?
1KEYBOARD = {
2 '2': 'abc',
3 '3': 'def',
4 '4': 'ghi',
5 '5': 'jkl',
6 '6': 'mno',
7 '7': 'pqrs',
8 '8': 'tuv',
9 '9': 'wxyz',
10}
11
12def letter_combinations_of_phone_number(digits):
13 def dfs(path, res):
14 if len(path) == len(digits):
15 res.append(''.join(path))
16 return
17
18 next_number = digits[len(path)]
19 for letter in KEYBOARD[next_number]:
20 path.append(letter)
21 dfs(path, res)
22 path.pop()
23
24 res = []
25 dfs([], res)
26 return res
27
1private static final Map<Character, char[]> KEYBOARD = Map.of(
2 '2', "abc".toCharArray(),
3 '3', "def".toCharArray(),
4 '4', "ghi".toCharArray(),
5 '5', "jkl".toCharArray(),
6 '6', "mno".toCharArray(),
7 '7', "pqrs".toCharArray(),
8 '8', "tuv".toCharArray(),
9 '9', "wxyz".toCharArray()
10);
11
12public static List<String> letterCombinationsOfPhoneNumber(String digits) {
13 List<String> res = new ArrayList<>();
14 dfs(new StringBuilder(), res, digits.toCharArray());
15 return res;
16}
17
18private static void dfs(StringBuilder path, List<String> res, char[] digits) {
19 if (path.length() == digits.length) {
20 res.add(path.toString());
21 return;
22 }
23 char next_digit = digits[path.length()];
24 for (char letter : KEYBOARD.get(next_digit)) {
25 path.append(letter);
26 dfs(path, res, digits);
27 path.deleteCharAt(path.length() - 1);
28 }
29}
30
1const KEYBOARD = {
2 '2': 'abc',
3 '3': 'def',
4 '4': 'ghi',
5 '5': 'jkl',
6 '6': 'mno',
7 '7': 'pqrs',
8 '8': 'tuv',
9 '9': 'wxyz',
10}
11
12function letter_combinations_of_phone_number(digits) {
13 let res = [];
14 dfs(digits, [], res);
15 return res;
16}
17
18function dfs(digits, path, res) {
19 if (path.length === digits.length) {
20 res.push(path.join(''));
21 return;
22 }
23 let next_number = digits.charAt(path.length);
24 for (let letter of KEYBOARD[next_number]) {
25 path.push(letter);
26 dfs(digits, path, res);
27 path.pop();
28 }
29}
30
Recommended Readings
https assets algo monster cover_photos dfs svg Depth First Search Prereqs Recursion Review problems recursion_intro Trees problems tree_intro With a solid understanding of recursion under our belts we are now ready to tackle one of the most useful techniques in coding interviews Depth First Search DFS As the name suggests
https assets algo monster cover_photos bfs svg Breadth First Search on Trees Hopefully by this time you've drunk enough DFS Kool Aid to understand its immense power and seen enough visualization to create a call stack in your mind Now let me introduce the companion spell Breadth First Search BFS
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Want a Structured Path to Master System Design Too? Donβt Miss This!