Skip to the solution
HardDSA12 min read

Longest increasing path in matrix — why DFS + memo beats brute force?

774 views

The problem

Question presented to candidate: "Given an m by n matrix of integers, return the length of the longest strictly increasing path, moving only up, down, left or right. Start with the brute force, explain why it is slow, then make it fast. Please write it in Python."

What a strong answer should cover:

  • The model: every cell is a node with an edge to each strictly larger neighbour; strictly increasing means no cycles, so it is a DAG, and the answer is its longest path.
  • Brute force: DFS from every cell exploring every increasing path is exponential, because the same cells are re-explored from many starts.
  • DFS + memo: the longest path starting at a cell does not depend on how you reached it, so cache it; each cell is solved once and each edge is followed once: O(m·n) time and space.
  • No visited set is needed (values strictly increase, so a path cannot revisit a cell), and the alternative is Kahn topological layering, which avoids recursion.
  • Python specifics: a nested dfs closing over a memo list of lists (or functools.lru_cache(maxsize=None) on a nested function), and the recursion limit: a 1 x 1000 strictly increasing row already raised RecursionError, so large inputs need the iterative topological version.

Clarifying questions expected:

  • "Strictly increasing, or is equal allowed?" (equal values would create cycles and break memoisation)
  • "Only four directions, no diagonals? Can the matrix be empty?"

Code / implementation expected: Yes — longest_increasing_path(matrix) in Python with DFS + memo; the Kahn layering version is a bonus.

  • dfs
  • memo
  • Google

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read · 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonDFS + memo on sample matrices, with one longest path rebuilt
PythonBrute-force DFS vs DFS + memo: counting calls
PythonKahn layering (no recursion), checked against DFS + memo

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 140 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

Alien Dictionary: given sorted words in an alien language, how do you derive the character order?

Continue