Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Shortest path (in steps) from the top-left to the bottom-right cell of a grid where 1 is a wall, if you may remove at most k walls. BFS over states (r, c, walls left).

Problem: Shortest path (in steps) from the top-left to the bottom-right cell of a grid where 1 is a wall, if you may remove at most k walls. BFS over states (r, c, walls left).
from collections import deque
def path(g, k):
    R, C = len(g), len(g[0])
    q, seen = deque([(0, 0, k, 0)]), {(0, 0, k)}
    while q:
        r, c, left, d = q.popleft()
        if (r, c) == (R - 1, C - 1): return d
        for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= x < R and 0 <= y < C:
                nl = left - g[x][y]
                if nl >= 0 and (x, y, nl) not in seen:
                    seen.add((x, y, nl)); q.append((x, y, nl, d + 1))
    return -1
g = [[0, 1, 1], [1, 1, 0], [1, 0, 0]]
print(path(g, 1), path(g, 2))
What is printed?
  1. A. 4 4
  2. B. -1 4
  3. C. -1 6
  4. D. 6 4

Correct answer: B. -1 4

Both neighbours of the start are walls, and every second step from them also hits a wall, so any route needs at least 2 removals: with k = 1 the target is unreachable (−1). With k = 2 a Manhattan-length path of 4 steps exists, e.g. right, down, down, right. The visited set must include the walls-left count.

More Coding Interview Problems questions

Exams that ask this topic