Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Rain falls on a 2-D height map. Compute the trapped water volume with a min-heap that grows inward from the border.
Problem: Rain falls on a 2-D height map. Compute the trapped water volume with a min-heap that grows inward from the border.
import heapq
def trap(h):
R, C = len(h), len(h[0]); seen = set(); pq = []
for r in range(R):
for c in range(C):
if r in (0, R - 1) or c in (0, C - 1): heapq.heappush(pq, (h[r][c], r, c)); seen.add((r, c))
water = 0
while pq:
lv, r, c = heapq.heappop(pq)
for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if 0 <= x < R and 0 <= y < C and (x, y) not in seen:
seen.add((x, y)); water += max(0, lv - h[x][y])
heapq.heappush(pq, (max(lv, h[x][y]), x, y))
return water
print(trap([[3,3,3,3,3],[3,1,2,1,3],[3,2,0,4,3],[3,3,1,3,3]]))What is printed?- A. 3
- B. 11
- C. 9
- D. 13
Correct answer: A. 3
Each inner cell fills to its 'spill height', the lowest possible maximum wall on a path to the border. The 0 at (2, 2) drains through the border gap of height 1, so it holds 1 unit; the 1s at (1, 1) and (1, 3) are enclosed by walls of height 2 and hold 1 unit each; the 2s hold nothing. Total 3.
More Coding Interview Problems questions
- Problem: Remove the fewest DISTINCT values so that at least half of the array's elements are removed (greedy on frequencies). python from…
- Problem: Find a target's index in a rotated sorted array of distinct values in O(log n). python def search(a, t): lo, hi = 0, len(a) - 1…
- Problem: You take trains in order; train i covers dist[i] km at a common integer speed, and every train except the last departs only at an…
- Problem: Koko eats from one pile per hour at speed k bananas/hour (if a pile has fewer, she finishes it and waits). Find the minimum k to…
- Problem: Length of the longest common subsequence of THREE strings (3-D DP). python def lcs3(a, b, c): dp = [[[0] (len(c) + 1) for in…
- Problem: Length of the longest strictly increasing path in a matrix (moves in 4 directions), with memoised DFS. python from functools…