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
Path Counting: Sum Divisible by K5243STARTENDPath 1: 5→2→3 = 10 (divisible by 2) ✓Path 2: 5→4→3 = 12 (divisible by 2) ✓Result: 2 valid paths for k=2
Understanding the Visualization
1
Input
Matrix with start at (0,0) and end at (m-1,n-1)
2
Process
Find all paths moving only right or down
3
Output
Count paths where sum of elements is divisible by k
Key Takeaway
🎯 Key Insight: Track remainder (sum % k) instead of full sum to efficiently count valid paths
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