Question bank

How would you count the number of islands in a 2D grid map consisting of '1's (land) and '0's (water), where an island is defined as a group of adjacent lands connected horizontally or vertically?

February 17, 2025Updated March 31, 20263 min read
MediumCodingData AnalysisProblem-SolvingAlgorithm DesignSoftware EngineerData Scientist
How would you count the number of islands in a 2D grid map consisting of '1's (land) and '0's (water), where an island is defined as a group of adjacent lands connected horizontally or vertically?

Approach When answering the question, "How would you count the number of islands in a 2D grid map consisting of '1's (land) and '0's (water), where an island is defined as a group of adjacent lands connected horizontally or vertically?" , follow this…

Approach

When answering the question, "How would you count the number of islands in a 2D grid map consisting of '1's (land) and '0's (water), where an island is defined as a group of adjacent lands connected horizontally or vertically?", follow this structured framework:

  1. Understand the Problem: Identify what constitutes an island and the grid representation.
  2. Choose a Method: Decide on a traversal technique (Depth-First Search (DFS) or Breadth-First Search (BFS)).
  3. Implement the Algorithm: Write pseudocode or actual code to demonstrate your solution.
  4. Explain Your Solution: Walk through the logic of your implementation.
  5. Discuss Complexity: Address time and space complexity of your approach.

Key Points

  • Definition Clarity: Clearly define what an island is.
  • Algorithm Selection: Be prepared to justify your choice of DFS or BFS.
  • Edge Cases: Consider scenarios like a grid full of water or land.
  • Efficiency: Discuss the use of visited data structures to avoid counting the same island multiple times.

Standard Response

To tackle the problem of counting the number of islands in a 2D grid, we can use the Depth-First Search (DFS) approach. Below is a structured explanation and implementation.

Step 1: Understand the Problem

An island is defined as a group of connected '1's (land) in the grid, where connectivity is only vertical or horizontal. Water is represented by '0's. Our goal is to count the distinct islands.

Step 2: Choose a Method

  • Start from any unvisited land cell (1).
  • Mark all connected land cells as visited.
  • Increment the island count every time we initiate a DFS from an unvisited land cell.
  • We can use Depth-First Search (DFS) to explore each island:

Step 3: Implement the Algorithm

Here is a sample implementation in Python:

def numIslands(grid):
 if not grid:
 return 0

 def dfs(i, j):
 if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == '0':
 return
 # Mark the current cell as visited by converting '1' to '0'
 grid[i][j] = '0'
 # Explore all adjacent cells (up, down, left, right)
 dfs(i - 1, j)
 dfs(i + 1, j)
 dfs(i, j - 1)
 dfs(i, j + 1)

 count = 0
 for i in range(len(grid)):
 for j in range(len(grid[0])):
 if grid[i][j] == '1': # Found an unvisited land
 dfs(i, j) # Start DFS to mark all connected lands
 count += 1 # Increment island count

 return count

Step 4: Explain Your Solution

  • Grid Traversal: We loop through each cell in the 2D grid.
  • DFS Execution: Upon finding an unvisited land cell (1), we initiate a DFS which marks all connected parts of the island as visited (changing '1' to '0').
  • Count Increment: Each time we start a DFS from an unvisited land, we increment our island count.

Step 5: Discuss Complexity

  • Time Complexity: O(M * N), where M is the number of rows and N is the number of columns. Each cell is visited once.
  • Space Complexity: O(M * N) in the worst case due to the recursion stack.

Tips & Variations

Common Mistakes to Avoid

  • Forgetting to mark cells as visited, leading to infinite loops.
  • Not considering edge cases, such as empty grids or grids with no islands.

Alternative Ways to Answer

  • BFS Approach: Instead of DFS, you could use BFS to explore the grid:
  • Implement BFS using a queue to track cells to visit.

Example BFS implementation:

VA

Verve AI Editorial Team

Question Bank

Related reads

Explore More Question Bank Entries

How would you implement an algorithm to serialize and deserialize an N-ary tree?
February 10, 2025Hard

How would you implement an algorithm to serialize and deserialize an N-ary tree?

Approach To effectively answer the interview question about implementing an algorithm to serialize and deserialize an N-ary tree, follow this structured framework: Understand the Problem : Define serialization and deserialization in the context of an N-ary…

Read answer guide
How would you implement an algorithm to set entire rows and columns to zero in an MxN matrix if any element is zero?
February 1, 2025Medium

How would you implement an algorithm to set entire rows and columns to zero in an MxN matrix if any element is zero?

Approach To effectively answer the interview question about implementing an algorithm to set entire rows and columns to zero in an MxN matrix if any element is zero, follow this structured framework: Understanding the Problem : Grasp the requirements and…

Read answer guide
How would you implement an algorithm to solve the N-Queens problem?
February 10, 2025Hard

How would you implement an algorithm to solve the N-Queens problem?

Approach To effectively answer the question, "How would you implement an algorithm to solve the N-Queens problem?", follow this structured framework: Understanding the Problem : Clearly define the N-Queens problem. Choosing an Algorithm : Discuss the…

Read answer guide
How would you implement an algorithm to efficiently solve the word search problem in a grid?
February 1, 2025Medium

How would you implement an algorithm to efficiently solve the word search problem in a grid?

Approach To effectively answer the question "How would you implement an algorithm to efficiently solve the word search problem in a grid?", follow this structured framework: Understand the Problem : Define what the word search problem entails. Identify…

Read answer guide
How would you implement an algorithm to sort a stack data structure?
January 4, 2025Medium

How would you implement an algorithm to sort a stack data structure?

Approach To effectively answer the interview question on implementing an algorithm to sort a stack data structure, follow this structured framework: Understand the Problem : Clearly articulate what is required when sorting a stack. Choose the Right Algorithm…

Read answer guide
How would you implement an algorithm to determine the number of ways to split a given string?
January 11, 2025Medium

How would you implement an algorithm to determine the number of ways to split a given string?

Approach When faced with the interview question, "How would you implement an algorithm to determine the number of ways to split a given string?" it's essential to break down your thought process into structured steps. Here’s a comprehensive framework to…

Read answer guide
How would you implement an algorithm to calculate the sum of all left leaves in a binary tree?
January 13, 2025Medium

How would you implement an algorithm to calculate the sum of all left leaves in a binary tree?

Approach To effectively answer the question, “How would you implement an algorithm to calculate the sum of all left leaves in a binary tree?”, follow this structured framework: Understand the Problem : Clarify the definition of left leaves in the context of…

Read answer guide
How can you implement an algorithm to calculate the number of ways to tile a floor?
January 20, 2025Medium

How can you implement an algorithm to calculate the number of ways to tile a floor?

Approach To effectively answer the question of implementing an algorithm to calculate the number of ways to tile a floor, follow this structured framework: Understand the Problem : Clearly define what is meant by "tiling a floor" and the constraints involved…

Read answer guide
How would you implement an algorithm to calculate the number of unique binary search trees that can be formed with 'n' distinct nodes?
January 20, 2025Hard

How would you implement an algorithm to calculate the number of unique binary search trees that can be formed with 'n' distinct nodes?

Approach To effectively answer the question on implementing an algorithm to calculate the number of unique binary search trees (BSTs) that can be formed with 'n' distinct nodes, follow this structured framework: Understand the Problem : Define what a binary…

Read answer guide