Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Length of the longest strictly increasing path in a matrix (moves in 4 directions), with memoised DFS.

Problem: Length of the longest strictly increasing path in a matrix (moves in 4 directions), with memoised DFS.
from functools import lru_cache
m = [[3, 4, 5], [3, 2, 6], [2, 2, 1]]
R, C = len(m), len(m[0])
@lru_cache(None)
def dfs(r, c):
    best = 1
    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 m[x][y] > m[r][c]:
            best = max(best, 1 + dfs(x, y))
    return best
print(max(dfs(r, c) for r in range(R) for c in range(C)))
What is printed?
  1. A. 5
  2. B. 4
  3. C. 6
  4. D. 3

Correct answer: B. 4

The chain 3 → 4 → 5 → 6 (top row, then down to 6) has length 4; 2 at (1,1) → 4 → 5 → 6 ties it. No 5-step chain exists because every cell adjacent to the starts of these chains is not smaller. Memoisation makes each cell's answer computed once: O(R·C).

More Coding Interview Problems questions

Exams that ask this topic