Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the longest increasing path in a matrix (moving up/down/left/right to strictly larger values).

Problem: Find the longest increasing path in a matrix (moving up/down/left/right to strictly larger values).
from functools import lru_cache
def lip(m):
    R, C = len(m), len(m[0])
    @lru_cache(None)
    def go(r, c):
        best = 1
        for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= nr < R and 0 <= nc < C and m[nr][nc] > m[r][c]:
                best = max(best, 1 + go(nr, nc))
        return best
    return max(go(r, c) for r in range(R) for c in range(C))
print(lip(((9, 9, 4), (6, 6, 8), (2, 1, 1))), lip(((3, 4, 5), (3, 2, 6), (2, 2, 1))))
What is printed?
  1. A. 4 5
  2. B. 3 4
  3. C. 4 4
  4. D. 5 4

Correct answer: C. 4 4

DFS with memoisation: strictly increasing moves cannot form cycles, so the grid is a DAG and each cell's answer is computed once. 1 → 2 → 6 → 9 and 3 → 4 → 5 → 6 both have length 4. O(R·C).

More Coding Interview Problems questions

Exams that ask this topic