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?- A. 4 4
- B. -1 4
- C. -1 6
- 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
- Problem: A lock has 4 wheels of digits 0–9; one move turns one wheel by ±1 (wrapping 9↔0). Starting at '0000', find the fewest moves to…
- Problem: Water level t floods every cell of height ≤ t. Find the smallest t at which you can swim from the top-left to the bottom-right…
- Problem: Connect all points with minimum total Manhattan-distance wiring (dense-graph Prim in O(n²)). python def mst(p): n = len(p); dist…
- Problem: Courses with prerequisites (u → v means u before v); any number of courses can be taken per semester. Find the minimum number of…
- Problem: Answer lowest-common-ancestor queries with binary lifting (up[j][v] = 2^j-th ancestor). python par = [-1, 0, 0, 1, 1, 2, 3, 3, 4…
- A COMPLETE binary tree has n nodes. Counting them by comparing the leftmost and rightmost depths at each node and recursing into only one…