Paths in Matrix Whose Sum Is Divisible by K — LeetCode 2435 Python Solution

HardArrayDynamic ProgrammingMatrix
Problem
#2435
Reading time
3 min

The 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.

Example

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.

Python solution

Python
class Solution:
    def numberOfPaths(self, grid: List[List[int]], K: int) -> int:
        mod = 10**9 + 7
        m, n = len(grid), len(grid[0])
        f = [[[0] * K for _ in range(n)] for _ in range(m)]
        f[0][0][grid[0][0] % K] = 1
        for i in range(m):
            for j in range(n):
                for k in range(K):
                    k0 = ((k - grid[i][j] % K) + K) % K
                    if i:
                        f[i][j][k] += f[i - 1][j][k0]
                    if j:
                        f[i][j][k] += f[i][j - 1][k0]
                    f[i][j][k] %= mod
        return f[m - 1][n - 1][0]

Complexity

MeasureComplexity
TimeO(m \times n \times K)
SpaceO(m \times n \times K), where m and n are the number of rows and columns of the matrix \textit{grid}, respectively, and K is the integer k from the problem auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2435. Paths in Matrix Whose Sum Is Divisible by K is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2435. Paths in Matrix Whose Sum Is Divisible by K?
LeetCode 2435. Paths in Matrix Whose Sum Is Divisible by K is rated Hard on LeetCode.
What is the time complexity of LeetCode 2435. Paths in Matrix Whose Sum Is Divisible by K?
The Python solution on this page runs in O(m \times n \times K).
What is the space complexity of LeetCode 2435. Paths in Matrix Whose Sum Is Divisible by K?
The Python solution on this page uses O(m \times n \times K), where m and n are the number of rows and columns of the matrix \textit{grid}, respectively, and K is the integer k from the problem auxiliary space.
What topics does LeetCode 2435. Paths in Matrix Whose Sum Is Divisible by K cover?
LeetCode 2435. Paths in Matrix Whose Sum Is Divisible by K is tagged Array, Dynamic Programming and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview