#2435
Paths in Matrix Whose Sum Is Divisible by K
HardArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^(m+n)) | O(m * n * k) |
| Space | O(m+n) | O(m * n * k) |
💡
Intuition
Time O(m * n * k)Space O(m * n * k)
Using dynamic programming, we can keep track of the number of ways to reach each cell with a specific sum modulo k. This way, we avoid recalculating paths and can efficiently count valid paths.
⚙️
Algorithm
3 steps- 1Step 1: Create a 3D DP array where dp[i][j][r] represents the number of ways to reach cell (i, j) with a sum that gives remainder r when divided by k.
- 2Step 2: Initialize dp[0][0][grid[0][0] % k] = 1.
- 3Step 3: Iterate through each cell, updating the DP table based on the possible moves (down and right) and the current sums.
solution.py20 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def countPaths(grid, k):
5 m, n = len(grid), len(grid[0])
6 dp = [[[0] * k for _ in range(n)] for _ in range(m)]
7 dp[0][0][grid[0][0] % k] = 1
8
9 for i in range(m):
10 for j in range(n):
11 for r in range(k):
12 if dp[i][j][r] > 0:
13 if i + 1 < m:
14 new_r = (r + grid[i + 1][j]) % k
15 dp[i + 1][j][new_r] = (dp[i + 1][j][new_r] + dp[i][j][r]) % MOD
16 if j + 1 < n:
17 new_r = (r + grid[i][j + 1]) % k
18 dp[i][j + 1][new_r] = (dp[i][j + 1][new_r] + dp[i][j][r]) % MOD
19
20 return dp[m - 1][n - 1][0]ℹ
Complexity note: This complexity arises because we maintain a 3D DP array that tracks the number of paths for each cell and each possible remainder.
- 1The sum of the elements matters only in terms of their remainders when divided by k.
- 2Dynamic programming allows us to efficiently count paths without redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.