Data Structures & AlgorithmsVery hardProduct company OA
Problem: Rain on a height grid flows to a neighbour with height ≤ the current cell. The west/north edge touches one sea, the east/south edge another. Count cells from which water can reach both seas: flood UPHILL from each coast and intersect.
Problem: Rain on a height grid flows to a neighbour with height ≤ the current cell. The west/north edge touches one sea, the east/south edge another. Count cells from which water can reach both seas: flood UPHILL from each coast and intersect.
def both(h):
R, C = len(h), len(h[0])
def reach(starts):
seen = set(starts); st = list(starts)
while st:
i, j = st.pop()
for ni, nj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
if 0 <= ni < R and 0 <= nj < C and (ni, nj) not in seen and h[ni][nj] >= h[i][j]:
seen.add((ni, nj)); st.append((ni, nj))
return seen
west = reach([(i, 0) for i in range(R)] + [(0, j) for j in range(C)])
east = reach([(i, C - 1) for i in range(R)] + [(R - 1, j) for j in range(C)])
return len(west & east)
print(both([[1, 2, 3], [8, 9, 4], [7, 6, 5]]), both([[3, 3, 4, 5], [2, 7, 6, 4], [1, 5, 2, 3], [4, 2, 1, 6]]))What is printed?- A. 7 6
- B. 9 5
- C. 7 5
- D. 5 7
Correct answer: C. 7 5
Running a downhill search from every cell costs O((RC)²). Reversing the flow – start from the coast and climb to cells with height ≥ the current one – needs just two O(R·C) floods. In the spiral grid every cell except (0, 0) (height 1, it can only drain west/north) and (0, 1) (height 2, its only lower neighbour is 1) reaches both seas → 7. The second grid gives 5.
More Coding Interview Problems questions
- Problem: A recursive routine splits a problem of size n into parts n/3 and 2n/3 and does n extra work: W(n) = W(n/3) + W(2n/3) + n. The…
- Problem: Find the bug: Dijkstra (finalising a node when it is popped) is run on a graph with one negative edge and compared with…
- Problem: Count integers in [1, N] whose decimal digits have no two adjacent equal digits, using digit DP with states (position, previous…
- Problem: Count all valid topological orderings of a small DAG (n ≤ 20) with a DP over subsets: from a set of already placed nodes, place…
- Problem: A traffic monitor reports, for every window of k consecutive minutes, the busiest minute's count, and the dashboard shows the SUM…
- Problem: Find the maximum sum of a non-empty subarray of a CIRCULAR array (a subarray may wrap from the end to the start). python def…