Paths in Matrix Whose Sum Is Divisible by K - Problem

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.

Return the number of paths where the sum of the elements on the path is divisible by k. Since the answer may be very large, return it modulo 10^9 + 7.

Input & Output

Example 1 — Basic Case
$ Input: grid = [[5,2,4],[3,0,5],[0,7,2]], k = 3
Output: 2
💡 Note: There are two paths with sum divisible by 3: Path 1: 5→2→4→5→2 = 18 (18%3=0), Path 2: 5→3→0→7→2 = 17... Actually checking: 5→2→0→7→2=16, 5→3→0→7→2=17. Need to verify paths carefully.
Example 2 — Small Grid
$ Input: grid = [[5,2],[4,3]], k = 2
Output: 2
💡 Note: Two paths: 5→2→3=10 (10%2=0) and 5→4→3=12 (12%2=0). Both sums are divisible by 2.
Example 3 — No Valid Paths
$ Input: grid = [[1,2],[3,4]], k = 10
Output: 0
💡 Note: Path 1: 1→2→4=7, Path 2: 1→3→4=8. Neither 7 nor 8 is divisible by 10.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 5 × 101
  • 0 ≤ grid[i][j] ≤ 100
  • 1 ≤ k ≤ 50

Visualization

Tap to expand
Paths in Matrix Divisible by K INPUT 3x3 Matrix Grid 5 2 4 3 0 5 0 7 2 S E Parameters grid = [[5,2,4], [3,0,5], [0,7,2]] k = 3 ALGORITHM STEPS 1 Define DP State dp[i][j][r] = paths to (i,j) with sum % k == r 2 Initialize Base dp[0][0][5%3] = 1 dp[0][0][2] = 1 3 Transition From (i-1,j) or (i,j-1) new_r = (r + grid[i][j]) % k 4 Answer Return dp[m-1][n-1][0] (paths with sum%k==0) DP at (2,2) for r=0: Path1: 5+3+0+7+2=17 17 % 3 = 2 (NO) Path2: 5+2+4+5+2=18 18 % 3 = 0 (OK) FINAL RESULT Valid Paths Highlighted Path 1 (sum=18) 5 2 4 3 0 5 0 7 2 Path 2 (sum=12) 5 2 4 3 0 5 0 7 2 Output: 2 Key Insight: Track remainder (sum % k) at each cell instead of actual sum. Use 3D DP: dp[i][j][r] counts paths to position (i,j) with path sum having remainder r when divided by k. Only k possible remainders (0 to k-1), making space O(m*n*k). Time complexity: O(m*n*k). Answer is dp[m-1][n-1][0]. TutorialsPoint - Paths in Matrix Whose Sum Is Divisible by K | Dynamic Programming Approach
Asked in
Google 25 Amazon 18 Microsoft 15
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen