Check if There is a Path With Equal Number of 0's And 1's — LeetCode 2510 Python Solution

MediumLeetCode PremiumArrayDynamic ProgrammingMatrix
Problem
#2510
Reading time
4 min

The problem

You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1).

Example

Input
grid = [[0,1,0,0],[0,1,0,0],[1,0,1,0]]
Output
true
Explanation
The path colored in blue in the above diagram is a valid path because we have 3 cells with a value of 1 and 3 with a value of 0. Since there is a valid path, we return true.

Python solution

Python
class Solution:
    def isThereAPath(self, grid: List[List[int]]) -> bool:
        @cache
        def dfs(i, j, k):
            if i >= m or j >= n:
                return False
            k += grid[i][j]
            if k > s or i + j + 1 - k > s:
                return False
            if i == m - 1 and j == n - 1:
                return k == s
            return dfs(i + 1, j, k) or dfs(i, j + 1, k)

        m, n = len(grid), len(grid[0])
        s = m + n - 1
        if s & 1:
            return False
        s >>= 1
        return dfs(0, 0, 0)

Complexity

MeasureComplexity
TimeO(m \times n \times (m + n))
SpaceO(n·m) or optimized auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2510. Check if There is a Path With Equal Number of 0's And 1's 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 2510. Check if There is a Path With Equal Number of 0's And 1's?
LeetCode 2510. Check if There is a Path With Equal Number of 0's And 1's is rated Medium on LeetCode.
What topics does LeetCode 2510. Check if There is a Path With Equal Number of 0's And 1's cover?
LeetCode 2510. Check if There is a Path With Equal Number of 0's And 1's is tagged Array, Dynamic Programming and Matrix on LeetCode.
Is LeetCode 2510. Check if There is a Path With Equal Number of 0's And 1's a premium problem?
Yes. LeetCode 2510. Check if There is a Path With Equal Number of 0's And 1's is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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