Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2328: Number of Increasing Paths in a Grid

In this guide, we solve Leetcode #2328 Number of Increasing Paths in a Grid in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Depth-First Search, Breadth-First Search, Graph, Topological Sort, Memoization, Array, Dynamic Programming, Matrix

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: grid = [[1,1],[3,4]] Output: 8 Explanation: The strictly increasing paths are: - Paths with length 1: [1], [1], [3], [4]. - Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4]. - Paths with length 3: [1 -> 3 -> 4]. The total number of paths is 4 + 3 + 1 = 8.

Python Solution

class Solution: def countPaths(self, grid: List[List[int]]) -> int: @cache def dfs(i: int, j: int) -> int: ans = 1 for a, b in pairwise((-1, 0, 1, 0, -1)): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and grid[i][j] < grid[x][y]: ans = (ans + dfs(x, y)) % mod return ans mod = 10**9 + 7 m, n = len(grid), len(grid[0]) return sum(dfs(i, j) for i in range(m) for j in range(n)) % mod

Complexity

The time complexity is O(m×n)O(m \times n)O(m×n), and the space complexity is O(m×n)O(m \times n)O(m×n). The space complexity is O(m×n)O(m \times n)O(m×n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy