2025-11-26 Daily Challenge

Today I have done leetcode's November LeetCoding Challenge with cpp.

November LeetCoding Challenge 26

Description

Paths in Matrix Whose Sum Is Divisible by K

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 109 + 7.

 

Example 1:

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.

Example 2:

Input: grid = [[0,0]], k = 5
Output: 1
Explanation: The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5.

Example 3:

Input: grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]], k = 1
Output: 10
Explanation: Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 5 * 104
  • 1 <= m * n <= 5 * 104
  • 0 <= grid[i][j] <= 100
  • 1 <= k <= 50

Solution

class Solution {
  const int MOD = 1e9 + 7;
public:
  int numberOfPaths(vector<vector<int>>& grid, int k) {
    int rows = grid.size();
    int cols = grid.front().size();
    vector<vector<vector<int>>> dp(rows, vector<vector<int>>(cols, vector<int>(k)));
    dp[0][0][grid[0][0] % k] = 1;
    for(int i = 0; i < rows; ++i) {
      for(int j = 0; j < cols; ++j) {
        int val = grid[i][j];
        if(i) {
          for(int s = 0; s < k; ++s) {
            dp[i][j][(s + val) % k] += dp[i - 1][j][s];
            dp[i][j][(s + val) % k] %= MOD;
          }
        }
        if(j) {
          for(int s = 0; s < k; ++s) {
            dp[i][j][(s + val) % k] += dp[i][j - 1][s];
            dp[i][j][(s + val) % k] %= MOD;
          }
        }
      }
    }
    return dp.back().back()[0];
  }
};

// Accepted
// 88/88 cases passed (211 ms)
// Your runtime beats 81.18 % of cpp submissions
// Your memory usage beats 79.06 % of cpp submissions (132.1 MB)