Leetcode #2435: Paths in Matrix Whose Sum Is Divisible by K
In this guide, we solve Leetcode #2435 Paths in Matrix Whose Sum Is Divisible by K 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.

Problem Statement
You are given a 0-indexed m x n integer matrix grid and an integer k. You are currently at position (0, 0) and you want to reach position (m - 1, n - 1) moving only down or right.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: 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 = [[5,2,4],[3,0,5],[0,7,2]], k = 3
Output: 2
Explanation: There are two paths where the sum of the elements on the path is divisible by k.
The first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3.
The second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3.
Python Solution
class Solution:
def numberOfPaths(self, grid: List[List[int]], K: int) -> int:
mod = 10**9 + 7
m, n = len(grid), len(grid[0])
f = [[[0] * K for _ in range(n)] for _ in range(m)]
f[0][0][grid[0][0] % K] = 1
for i in range(m):
for j in range(n):
for k in range(K):
k0 = ((k - grid[i][j] % K) + K) % K
if i:
f[i][j][k] += f[i - 1][j][k0]
if j:
f[i][j][k] += f[i][j - 1][k0]
f[i][j][k] %= mod
return f[m - 1][n - 1][0]
Complexity
The time complexity is and the space complexity is , where and are the number of rows and columns of the matrix , respectively, and is the integer from the problem. The space complexity is , where and are the number of rows and columns of the matrix , respectively, and is the integer from the problem.
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.