Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Return the number of steps to reach the exit of a maze grid ('.' open, '+' wall) from an entrance, where an exit is an open border cell other than the entrance.
Problem: Return the number of steps to reach the exit of a maze grid ('.' open, '+' wall) from an entrance, where an exit is an open border cell other than the entrance.
from collections import deque
def nearest_exit(m, start):
R, C = len(m), len(m[0]); q = deque([(*start, 0)]); seen = {tuple(start)}
while q:
r, c, d = q.popleft()
if (r, c) != tuple(start) and (r in (0, R - 1) or c in (0, C - 1)): return d
for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if 0 <= nr < R and 0 <= nc < C and m[nr][nc] == '.' and (nr, nc) not in seen:
seen.add((nr, nc)); q.append((nr, nc, d + 1))
return -1
print(nearest_exit(["++.+", "...+", "+++."], [1, 2]), nearest_exit(["++", "+."], [1, 1]))What is printed?- A. 1 -1
- B. 2 -1
- C. 1 0
- D. 3 -1
Correct answer: A. 1 -1
BFS returns the first border cell reached, excluding the entrance itself. From (1, 2), moving up to (0, 2) reaches the border in 1 step. In the second maze the only open cell is the entrance, so there is no exit → −1 (returning 0 would wrongly count the entrance). O(R·C).
More Coding Interview Problems questions
- Problem: Count paths modulo 10⁹ + 7 from the top-left to the bottom-right of a 3 × 3 board whose centre is blocked, moving right, down or…
- Problem: Find the maximum number of points you can collect in a grid going right/down from top-left to bottom-right and then reconstruct…
- Problem: n ≤ 10⁵ tasks with durations and deadlines; complete as many tasks as possible, one at a time, each finishing by its deadline…
- Problem: Find the median of two sorted arrays of sizes m and n (up to 10⁶ each) in better than linear time. What is the optimal complexity?
- Problem: A social graph has V = 10⁶ users and E = 10⁷ friendships. You must store it to run BFS. Which representation is appropriate and…
- Problem: Given 'a/b = k' equations (e.g. a/b = 2, b/c = 3), answer queries like a/c. Which model and algorithm fit?