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?
  1. A. 7 6
  2. B. 9 5
  3. C. 7 5
  4. 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

Exams that ask this topic