Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Count islands (groups of '1' cells connected up, down, left or right) on a satellite grid.
Problem: Count islands (groups of '1' cells connected up, down, left or right) on a satellite grid.
def islands(g):
R, C = len(g), len(g[0]); seen = set(); n = 0
def dfs(r, c):
if not (0 <= r < R and 0 <= c < C) or g[r][c] != '1' or (r, c) in seen: return
seen.add((r, c))
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): dfs(r + dr, c + dc)
for r in range(R):
for c in range(C):
if g[r][c] == '1' and (r, c) not in seen:
n += 1; dfs(r, c)
return n
print(islands(["11000", "01001", "10011", "00000", "10101"]))What is printed?- A. 5
- B. 10
- C. 6
- D. 3
Correct answer: C. 6
Each unvisited land cell starts a DFS that marks its whole island: {(0,0),(0,1),(1,1)}, {(1,4),(2,3),(2,4)}, {(2,0)} and three single cells in the last row → 6. Allowing diagonal moves merges (1,1) with (2,0) and gives 5; counting land cells gives 10; a loop bound of range(R − 1) skips the last row and gives 3.
More Coding Interview Problems questions
- Problem: In a grid of fresh (1) and rotten (2) oranges, every minute rot spreads to 4-neighbours. Return the minutes until no fresh orange…
- Problem: Courses with prerequisites [a, b] (b before a). Return one valid order using Kahn's algorithm with a min-heap for ties, or [] if…
- Problem: Detect a cycle in a directed dependency graph with three-colour DFS. python def hascycle(n, edges): adj = [[] for in range(n)]…
- Problem: Find the shortest travel time from node 0 to every node in a road network with non-negative weights. python import heapq def…
- Problem: A network has V = 10⁵ routers and E = 2 × 10⁵ links with latencies that can be negative (but no negative cycle). Which…
- Problem: Union-find with path compression answers which friends are in the same circle. How many circles remain after the unions? python…