Magicsheet logo

Paths in Matrix Whose Sum Is Divisible by K

Hard
25%
Updated 8/1/2025

Asked by 1 Company

Paths in Matrix Whose Sum Is Divisible by K

What is this problem about?

The Paths in Matrix Whose Sum Is Divisible by K problem asks you to count all paths from the top-left to bottom-right of a grid (moving only right or down) where the path sum is divisible by k. This hard coding problem uses DP with modular arithmetic as an extra dimension. The array, matrix, and dynamic programming interview pattern with modular state tracking is the core.

Why is this asked in interviews?

Google asks this because it extends standard grid path counting with a divisibility constraint. The key insight: instead of tracking exact sums (too large), track sum mod k as the DP state. The array, matrix, and dynamic programming interview pattern is demonstrated with this elegant state reduction.

Algorithmic pattern used

3D DP with modular state. dp[i][j][r] = number of paths to cell (i,j) with sum ≡ r (mod k). Transition: dp[i][j][(r + grid[i][j]) % k] += dp[i-1][j][r] + dp[i][j-1][r]. Initialize: dp[0][0][grid[0][0] % k] = 1. Answer: dp[m-1][n-1][0].

Example explanation

Grid=[[5,2],[4,3]], k=3. Paths: (0,0)→(0,1)→(1,1): 5+2+3=10. 10%3≠0. (0,0)→(1,0)→(1,1): 5+4+3=12. 12%3=0 ✓. Count = 1.

DP: dp[0][0][5%3=2]=1. dp[0][1][2+2%3=1]=1. dp[1][0][2+4%3=2+1=0]=1. dp[1][1]: from dp[0][1][1] with +3%3=0: r=1+0=1→count=1. From dp[1][0][0] with +3%3=0: r=0→count=1. dp[1][1][1]+=1, dp[1][1][0]+=1. Answer=dp[1][1][0]=1 ✓.

Common mistakes candidates make

  • Tracking exact sums (overflows for large grids).
  • Off-by-one in modular addition ((r + grid[i][j]) % k).
  • Incorrect initialization (only dp[0][0][grid[0][0]%k]=1, not dp[0][0][0]=1).
  • Not accounting for all k remainder states in the DP.

Interview preparation tip

Grid path counting with divisibility constraints always uses sum mod k as an extra DP state. This reduces the state space from O(mn * max_sum) to O(mn * k). Practice this approach on: "number of paths with sum divisible by k in an array" (1D version), then extend to 2D grids. The modular DP pattern generalizes to any "count paths satisfying a divisibility property."

Similar Questions