Compute max reachable cells per threshold
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to reason about constrained grid reachability and efficient handling of multiple threshold queries, testing skills in reachability analysis, graph traversal concepts, and query-driven precomputation.
Constraints
- 1 <= m, n <= 1000
- 1 <= m * n <= 100000
- 1 <= len(limits) <= 100000
- -10^9 <= terrain[r][c], limits[i] <= 10^9
Examples
Input: ([[1, 4, 2, 8], [0, 4, 0, 8], [1, 2, 0, 8]], [8, 2])
Expected Output: [9, 3]
Explanation: For L = 8, every cell except the three cells with value 8 is allowed and reachable, so the score is 9. For L = 2, only the connected component {(0,0), (1,0), (2,0)} is reachable.
Input: ([[2, 5, 7], [3, 5, 1]], [5, 6, 2])
Expected Output: [2, 5, 0]
Explanation: For L = 5, only values less than 5 are allowed, so you can reach (0,0) and (1,0). For L = 6, every cell except 7 is allowed and all 5 such cells are connected to the start. For L = 2, the start cell is not allowed, so the score is 0.
Input: ([[5]], [4, 5, 6])
Expected Output: [0, 0, 1]
Explanation: This checks the strict inequality. A limit of 4 or 5 cannot enter the only cell because 5 is not less than the limit. A limit of 6 can, so the score is 1.
Input: ([[-1, -1], [2, -3]], [-2, 0, 3])
Expected Output: [0, 3, 4]
Explanation: For L = -2, the start cell -1 is not allowed, so the score is 0. For L = 0, the three negative cells are reachable. For L = 3, all four cells are allowed and reachable.
Input: ([[1, 100, 1], [1, 100, 1], [1, 1, 1]], [2, 101, 1])
Expected Output: [7, 9, 0]
Explanation: For L = 2, all cells with value 1 are allowed, and all 7 of them are connected through the bottom path. For L = 101, every cell is allowed, so the score is 9. For L = 1, no cell is allowed because the rule is strictly greater.
Hints
- If you sort the queries by threshold, the set of reachable cells only grows as the threshold increases.
- Use a min-heap to expand the reachable frontier in order of terrain value, so each cell is processed at most once.