Longest Ascending Orthogonal Path in a Matrix

Medium · Coding & Algorithms · Backend Engineer · Onsite

Problem Statement

You are given a rectangular integer grid matrix with R rows and C columns. Compute the maximum number of cells contained in any path whose cell values strictly increase at every step.

Implement the function:

def longest_increasing_path(matrix: list[list[int]]) -> int:

A path must obey the following movement rules:

  • Starting from any cell (r, c), each move goes one step up, down, left, or right to an adjacent cell (nr, nc) inside the grid with matrix[nr][nc] > matrix[r][c].
  • Stepping onto a neighbor with an equal or smaller value is not allowed.
  • Diagonal steps are forbidden, and the grid does not wrap across its outer borders (row 0 does not border row R - 1, and column 0 does not border column C - 1).
  • Standing on a single cell with zero moves counts as a valid path of 1 cell, so the result is always at least 1. Because values grow strictly on each move, no cell can appear twice on the same path.
  • Return the cell count of the longest valid path as an integer.

Examples

Example 1

Input: matrix = [
  [7, 5, 6],
  [2, 4, 8],
  [1, 3, 3]
]
Output: 6

Starting at (2, 0) (value 1), we can climb 1 -> 2 -> 4 -> 5 -> 6 -> 8 (or 1 -> 3 -> 4 -> 5 -> 6 -> 8), visiting 6 cells using only horizontal and vertical steps. Note that the two adjacent 3s on the bottom row cannot step to one another because growth must be strict.

Example 2

Input: matrix = [
  [5, 5, 2],
  [4, 2, 9]
]
Output: 3

Starting at (1, 1) (value 2), moving left to (1, 0) (4) and then up to (0, 0) (5) yields 2 -> 4 -> 5 of length 3. Continuing right onto the second 5 at (0, 1) is disallowed because 5 is not strictly greater than 5, and jumping diagonally from (0, 1) to 9 at (1, 2) is also disallowed.

Example 3

Input: matrix = [[10, 8, 2, 6, 9]]
Output: 3

From 2 at column 2, we can walk left along 2 -> 8 -> 10 or right along 2 -> 6 -> 9, each covering 3 cells. Column 4 (9) does not wrap back to column 0 (10).

Constraints

  • 1 <= R <= 200, where R = len(matrix)
  • 1 <= C <= 200, where C = len(matrix[r]) for every row 0 <= r < R
  • 0 <= matrix[r][c] <= 2^31 - 1

Step-by-step walkthrough

  1. Understand the rules and movement

    We are given an R x C grid of non-negative integers (1 <= R, C <= 200, up to 40,000 cells). We want the number of cells on the longest path where:

    • every move steps to an orthogonal neighbor (up, down, left, or right — never diagonal);
    • moves stay inside the grid (no wrapping from the last column back to the first, or from the bottom row back to the top);
    • every move goes to a strictly greater number (next_value > current_value).
    Allowed moves from X:          Forbidden moves:
          [up]                     - Diagonal steps
    [left]  X  [right]             - Equal values (5 -> 5)
         [down]                    - Wrapping across borders
    

    A path can start at any cell, and a single cell by itself counts as a path of length 1.

    Notice an important gift from the strict > rule: a valid path can never visit the same cell twice. Every step climbs to a strictly larger number, so it is impossible to circle back to an earlier, smaller cell. We never need a visited set to prevent loops.

  2. Why plain depth-first search is too slow

    A natural first idea is to start at each cell, try every neighbor with a larger value recursively, and return the longest chain of steps found.

    On a tiny grid, this brute-force depth-first search (DFS) gets the right answer, which makes it useful for testing. On a 200 x 200 grid, however, different starting paths constantly merge into the same cells and recompute the exact same future steps from scratch:

    Grid where matrix[r][c] = r + c:
      0 -> 1 -> 2
      |    |    |
      v    v    v
      1 -> 2 -> 3
      |    |    |
      v    v    v
      2 -> 3 -> 4
    

    Both 0 -> 1 (top) -> 2 (center) and 0 -> 1 (left) -> 2 (center) arrive at the center 2, and plain DFS explores everything after that center 2 twice. Across a 200 x 200 grid of r + c, every right/down route from top-left to bottom-right is strictly increasing — there are C(398, 199) such routes (a 119-digit number!), so plain DFS will never finish.

  3. Key insight: remember the best path starting at each cell

    Notice that once you arrive at cell (r, c), how you got there does not affect where you can go next. Because any step you take next only requires neighbor_value > matrix[r][c], the longest continuation depends only on (r, c).

    Let best[r][c] be the number of cells on the longest strictly increasing path that starts at (r, c):

    • If (r, c) has no strictly larger orthogonal neighbor, the path must stop right there, so best[r][c] = 1.
    • Otherwise, the path takes 1 step from (r, c) into whichever strictly larger neighbor (nr, nc) has the largest best[nr][nc]:
    best[r][c] = 1                                    (if no neighbor > matrix[r][c])
    best[r][c] = 1 + max(best[nr][nc])                (over orthogonal neighbors with matrix[nr][nc] > matrix[r][c])
    

    Once best[r][c] is filled in for every cell, the overall answer is simply the maximum value anywhere in best.

  4. Process cells from largest value to smallest

    To compute best[r][c], we need best[nr][nc] to already be finished for every neighbor with a larger value. How do we guarantee larger values are always finished first?

    We could write a recursive function with a cache, but on a 200 x 200 grid containing one long winding snake of 40,000 increasing numbers, recursion would call itself 40,000 levels deep and crash against Python's default 1,000-call recursion limit (RecursionError).

    Instead, we can sort all cells from largest value to smallest and loop over them in plain Python:

    • When we stand on the largest number in the entire grid, no neighbor is larger, so its best is immediately 1.
    • Whenever we process any cell with value v, every cell with a value greater than v appeared earlier in the sorted list, so best[nr][nc] for every valid next step is already final!
    • Cells with equal values can appear in any order relative to one another because a path cannot step between equal values anyway.
    rows = len(matrix)
    cols = len(matrix[0])
    
    # Phase 1: Collect every cell as (cell_value, row, col), e.g. [(8, 1, 2), (7, 0, 0), ...],
    # and sort from largest value to smallest so higher neighbors are always solved first.
    cells = []
    for r in range(rows):
        for c in range(cols):
            cells.append((matrix[r][c], r, c))
    cells.sort(reverse=True)
    
  5. Fill the DP table cell by cell

    We initialize every entry in best to 1 (the single-cell path) and longest_overall to 1. Then, walking through cells in decreasing value order, we inspect each cell's four orthogonal neighbors.

    Pay close attention to the bounds check 0 <= nr < rows and 0 <= nc < cols. In Python, forgetting 0 <= nc is a sneaky bug: matrix[r][-1] does not raise IndexError — it silently reads the last column of row r, creating the exact edge wrap-around that the problem forbids!

    # Four orthogonal step offsets (row_delta, col_delta): down, up, right, left.
    DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    
    # best[r][c]: number of cells on the longest strictly increasing path starting at (r, c).
    # Every single cell forms a valid path of length 1 on its own.
    best = [[1] * cols for _ in range(rows)]
    longest_overall = 1
    
    # Phase 2: Compute best[r][c] in decreasing value order using already-finished neighbors.
    for value, r, c in cells:
        for dr, dc in DIRECTIONS:
            nr = r + dr
            nc = c + dc
            # Check 0 <= nr and 0 <= nc explicitly: Python negative indices like matrix[r][-1]
            # would silently wrap around to the last column instead of raising an error.
            in_bounds = 0 <= nr < rows and 0 <= nc < cols
            # Strict '>' is required because equal adjacent values cannot follow each other.
            if in_bounds and matrix[nr][nc] > value:
                candidate_length = 1 + best[nr][nc]
                if candidate_length > best[r][c]:
                    best[r][c] = candidate_length
    
        if best[r][c] > longest_overall:
            longest_overall = best[r][c]
    
  6. Trace on concrete grids

    Let's trace Example 2, matrix = [[5, 5, 2], [4, 2, 9]]:

    matrix:          sorted cells (value, r, c):
    [ 5, 5, 2 ]      1. (9, 1, 2)   4. (4, 1, 0)
    [ 4, 2, 9 ]      2. (5, 0, 1)   5. (2, 1, 1)
                     3. (5, 0, 0)   6. (2, 0, 2)
    
    After 9 and both 5s:     After (4, 1, 0):         After both 2s:
    best = [ 1, 1, 1 ]       best = [ 1, 1, 1 ]       best = [ 1, 1, 2 ]
           [ 1, 1, 1 ]              [ 2, 1, 1 ]              [ 2, 3, 1 ]
    
    1. (9, 1, 2): orthogonal neighbors are 2 at (0, 2) and 2 at (1, 1). Neither is > 9, so best[1][2] stays 1.
    2. (5, 0, 1) and (5, 0, 0): the two 5s cannot step onto each other (5 > 5 is false), and 9 at (1, 2) is diagonal from (0, 1), so both stay 1.
    3. (4, 1, 0): neighbor 5 at (0, 0) has best = 1, giving best[1][0] = 1 + 1 = 2 (4 -> 5).
    4. (2, 1, 1): neighbors 5 (best = 1), 4 (best = 2), and 9 (best = 1) are all > 2. Stepping to 4 wins with 1 + 2 = 3 (2 -> 4 -> 5).
    5. (2, 0, 2): neighbors 5 and 9 both have best = 1, giving best[0][2] = 2. longest_overall = 3.

    And on Example 3, matrix = [[10, 8, 2, 6, 9]]:

    Cell processed     Valid '>' neighbors                Updated best row
    (10, 0, 0)         none (col -1 blocked)              [1, 1, 1, 1, 1]
    (9,  0, 4)         none (col  5 blocked)              [1, 1, 1, 1, 1]
    (8,  0, 1)         10 at (0,0) -> 1 + 1 = 2           [1, 2, 1, 1, 1]
    (6,  0, 3)         9  at (0,4) -> 1 + 1 = 2           [1, 2, 1, 2, 1]
    (2,  0, 2)         8 gives 1+2=3; 6 gives 1+2=3       [1, 2, 3, 2, 1] -> answer = 3
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Four orthogonal step offsets (row_delta, col_delta): down, up, right, left.
    DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    
    
    def longest_increasing_path(matrix: list[list[int]]) -> int:
        rows = len(matrix)
        cols = len(matrix[0])
    
        # Phase 1: Collect every cell as (cell_value, row, col), e.g. [(8, 1, 2), (7, 0, 0), ...],
        # and sort from largest value to smallest so higher neighbors are always solved first.
        cells = []
        for r in range(rows):
            for c in range(cols):
                cells.append((matrix[r][c], r, c))
        cells.sort(reverse=True)
    
        # best[r][c]: number of cells on the longest strictly increasing path starting at (r, c).
        # Every single cell forms a valid path of length 1 on its own.
        best = [[1] * cols for _ in range(rows)]
        longest_overall = 1
    
        # Phase 2: Compute best[r][c] in decreasing value order using already-finished neighbors.
        for value, r, c in cells:
            for dr, dc in DIRECTIONS:
                nr = r + dr
                nc = c + dc
                # Check 0 <= nr and 0 <= nc explicitly: Python negative indices like matrix[r][-1]
                # would silently wrap around to the last column instead of raising an error.
                in_bounds = 0 <= nr < rows and 0 <= nc < cols
                # Strict '>' is required because equal adjacent values cannot follow each other.
                if in_bounds and matrix[nr][nc] > value:
                    candidate_length = 1 + best[nr][nc]
                    if candidate_length > best[r][c]:
                        best[r][c] = candidate_length
    
            if best[r][c] > longest_overall:
                longest_overall = best[r][c]
    
        return longest_overall
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine hiking uphill on a grid of mountain elevations where each step can go north, south, east, or west, and must step onto a strictly higher elevation. Because you can only climb higher, your trail forms a directed acyclic graph (DAG) — a network of one-way arrows that can never loop back in a circle. If you start at the highest peak on the map, you cannot climb anywhere higher, so the longest trail from that cell is 1. If you then work backward from the highest elevations down to the lowest valleys using dynamic programming (solving each cell once, saving its answer in a table, and reusing it), every time you stand on a cell you already know the longest uphill trail from each higher neighbor around you: just pick the best higher neighbor and add 1.

A naive depth-first search (DFS) (following one uphill trail as far as possible before backtracking to try another branch) from every cell without saving results fails because separate trails constantly merge onto the same cell and recompute the entire remaining climb over and over, taking exponential time on grids like matrix[r][c] = r + c. Even recursive memoization (caching function results by their (row, col) arguments) hits a practical snag in Python: on a 200 x 200 grid with a single winding 40,000-cell path, recursion goes 40,000 calls deep and crashes against Python's default 1,000-call recursion limit. Sorting the cells from largest value to smallest avoids recursion completely.

Walk through Example 2, matrix = [[5, 5, 2], [4, 2, 9]]:

  1. Sort all (value, row, col) tuples descending: (9, 1, 2), (5, 0, 1), (5, 0, 0), (4, 1, 0), (2, 1, 1), (2, 0, 2), and start best filled with 1s.
  2. Process 9 at (1, 2) and both 5s at (0, 1) and (0, 0): none of them has a strictly larger orthogonal neighbor (5 cannot step onto 5, and 9 is diagonal from (0, 1)), so their best entries stay 1.
  3. Process 4 at (1, 0): its upper neighbor 5 at (0, 0) has best = 1, giving best[1][0] = 1 + 1 = 2 (4 -> 5).
  4. Process 2 at (1, 1) and 2 at (0, 2): (1, 1) can step to 5 (best = 1), 4 (best = 2), or 9 (best = 1), picking 4 for 1 + 2 = 3 (2 -> 4 -> 5), while (0, 2) gets 2. The maximum across the grid is 3.

Complexity

Let N = R * C be the total number of cells in the grid (at most 200 * 200 = 40,000).

  • Time: O(N log N). Building the list of N cells takes O(N) time, sorting the N tuples from largest to smallest takes O(N log N) time, and the single dynamic programming pass inspects at most 4 neighbors per cell in O(N) time, so sorting dominates.
  • Space: O(N). We store N (value, row, col) tuples in cells and an R x C table best of N integers.

Edge cases

  • 1 x 1 grid: no neighbors exist, and the single cell itself gives length 1.
  • All values equal: no neighbor is strictly greater, so every cell stays at 1 and the answer is 1.
  • Equal neighbors in the middle of a run: [[1, 2, 2, 3]] breaks at the duplicate 2, returning 2 (1 -> 2 or 2 -> 3), not 4.
  • Single row or single column: [[10, 8, 2, 6, 9]] returns 3 (2 -> 8 -> 10 or 2 -> 6 -> 9) because the last cell does not wrap around to the first.
  • Negative index wrap-around trap: in [[1, 0, 5]], cell (0, 0) must not read matrix[0][-1] == 5; explicit 0 <= nr and 0 <= nc checks keep the answer at 2.
  • Winding paths that turn in all four directions: paths can snake left, right, up, and down up to N = 40,000 cells without overflowing the call stack because our loop uses zero recursion.
  • Extreme values (0 and 2^31 - 1): cell values are only compared (>), never added together, so large cell values cannot overflow.

Common mistakes

  • Running plain DFS without caching: explores the same suffixes exponentially many times and times out on medium-sized grids.
  • Using >= instead of strict >: allows stepping between equal neighbors, violating the problem rule and creating two-cell cycles (5 <-> 5).
  • Omitting 0 <= nr or 0 <= nc in Python: negative indices like -1 are legal in Python lists and quietly read from the opposite edge of the grid instead of raising an error.
  • Allowing 8 directions instead of 4: adding diagonal offsets like (1, 1) lets paths jump corners that the statement forbids.
  • Relying on default recursion limits for memoized DFS: a 20,000-cell snake path raises RecursionError under Python's 1,000-frame limit, and on Python 3.12+ functools.lru_cache can still hit the C-stack recursion limit even after sys.setrecursionlimit.
  • Counting edges (steps) instead of cells: initializing best to 0 instead of 1 undercounts every path by 1.

Alternative approaches

  • Top-down memoized DFS (with an explicit stack or custom cache): define best(r, c) recursively and cache each cell's result on first visit. This runs in O(N) time and O(N) space without sorting, though in Python iterative bottom-up code is safer against deep recursion limits on long winding paths.
  • Topological peeling (Kahn's algorithm): topological sorting orders a one-way graph by repeatedly removing nodes that have no outgoing arrows left. Count how many strictly larger neighbors each cell has (out_degree), push all peak cells with out_degree == 0 into a queue, and peel the grid layer by layer while decrementing smaller neighbors' counts; the number of layers peeled equals the longest path in O(N) time and O(N) space.

Follow-up questions

  • How would you return the actual sequence of coordinates along a longest path instead of only its cell count? Create a companion table next_cell[r][c] initialized to None, and whenever 1 + best[nr][nc] improves best[r][c], record next_cell[r][c] = (nr, nc). Also remember the (start_r, start_c) cell that achieved longest_overall. At the end, follow next_cell pointers starting from (start_r, start_c) until None to reconstruct the full path in O(N) extra space and O(path length) time.
  • How does the algorithm change if diagonal steps to all eight surrounding neighbors are also permitted? You only add the four diagonal offsets (1, 1), (1, -1), (-1, 1), and (-1, -1) to DIRECTIONS. Because every move still requires a strictly greater value (>), paths still cannot cycle and sorting from largest value to smallest remains completely valid. Each cell checks 8 neighbors instead of 4, keeping time complexity at O(N log N) and space at O(N).
  • Why does dynamic programming break if consecutive cells may have equal values (>=) while still forbidding repeated cells? Equal neighbors create cycles inside flat plateaus of identical numbers, so the best continuation from (r, c) now depends on which plateau cells were already visited on the way there. Finding the longest non-repeating path inside a grid plateau is NP-hard (a class of problems with no known polynomial-time algorithm because finding a path that visits every cell in a grid region is NP-complete). In an interview, point out why standard DP breaks on plateaus and propose backtracking with visited pruning if plateaus are tiny, or ask whether consecutive equal cells represent a single merged region.

Follow-up questions

Similar questions

More New Relic interview questions

All 3 New Relic questions →