Data Structures & AlgorithmsHardGoogle · Flipkart interview
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 cell (minimise the maximum height on the path).
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 cell (minimise the maximum height on the path).
import heapq
def swim(g):
n = len(g); h = [(g[0][0], 0, 0)]; seen = {(0, 0)}; best = 0
while h:
t, r, c = heapq.heappop(h); best = max(best, t)
if (r, c) == (n - 1, n - 1): return best
for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if 0 <= x < n and 0 <= y < n and (x, y) not in seen:
seen.add((x, y)); heapq.heappush(h, (g[x][y], x, y))
print(swim([[0, 5, 9], [2, 7, 6], [3, 8, 4]]))What is printed?- A. 8
- B. 4
- C. 9
- D. 7
Correct answer: D. 7
Always expanding the lowest reachable cell is a Dijkstra/Prim variant on the bottleneck: the route 0 → 5 → 7 → 6 → 4 never exceeds 7, while every other route crosses 8 or 9. Minimising the path SUM (0 → 2 → 3 → 8 → 4) or stepping to the smallest neighbour gives 8, returning the popped height t instead of the running max gives 4, and the border path along the top row gives 9.
More Coding Interview Problems questions
- 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…
- Problem: Rebuild a BST from its preorder traversal (using value bounds) and print its postorder. python def postfrompre(pre): i, out = 0…
- Problem: For every node of a tree, compute the sum of distances to all other nodes in O(n) with re-rooting: ans[child] = ans[parent] −…