Watch 2 video solutions for Check if There is a Path With Equal Number of 0's And 1's, a medium level problem involving Array, Dynamic Programming, Matrix. This walkthrough by Code-Yao has 416 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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).
Return true if there is a path from (0, 0) to (m - 1, n - 1) that visits an equal number of 0's and 1's. Otherwise return false.
Example 1:
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.
Example 2:
Input: grid = [[1,1,0],[0,0,1],[1,0,0]] Output: false Explanation: There is no path in this grid with an equal number of 0's and 1's.
Constraints:
m == grid.lengthn == grid[i].length2 <= m, n <= 100grid[i][j] is either 0 or 1.Problem Overview: You start at the top-left cell of a binary matrix and can only move right or down. The goal is to reach the bottom-right cell using a path that contains the same number of 0s and 1s. The path length is fixed at m + n - 1, so a valid path must have exactly half zeros and half ones.
A quick observation simplifies the problem: if m + n - 1 is odd, the path length cannot be split evenly between zeros and ones. In that case, the answer is immediately false.
Approach 1: Brute Force DFS (Exponential Time)
Enumerate every possible path from (0,0) to (m-1,n-1) using depth‑first search. At each step, move either right or down while tracking how many zeros and ones you have seen so far. When the path reaches the bottom-right cell, check whether the counts are equal.
This approach explores the full decision tree of paths, which is roughly O(2^(m+n)) in the worst case. Space complexity is O(m+n) for the recursion stack. It works for very small grids but quickly becomes infeasible as the grid grows.
Approach 2: DFS with Memoization (Dynamic Programming) (Time: O(m * n * (m+n)), Space: O(m * n * (m+n)))
The key insight: different paths can reach the same cell with the same difference between the number of ones and zeros. Once you know that state leads to failure, you never need to recompute it.
Convert the problem into a running balance: treat 1 as +1 and 0 as -1. A valid path ends with total sum 0. During DFS, track the current cell (r, c) and the running sum. Use memoization to store states (r, c, balance) that have already been explored.
Pruning improves performance further. From a given position, you know how many steps remain before reaching the end. If the remaining steps cannot compensate for the current balance, the path cannot reach zero. That branch can be cut early.
This transforms the brute-force search into a dynamic programming problem over a matrix, caching repeated states. The algorithm visits each cell with a limited range of balances, resulting in roughly O(m * n * (m+n)) time and the same order of memory.
The technique combines DFS state exploration with memoization, a classic pattern in dynamic programming problems that operate on grids or paths.
Recommended for interviews: DFS with memoization is the expected solution. Brute force shows you understand the path search space, but memoization demonstrates the ability to identify overlapping subproblems and apply array and grid DP optimization. Interviewers usually expect the parity check plus memoized search with pruning.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force DFS | O(2^(m+n)) | O(m+n) | Small grids or when first reasoning about all possible paths |
| DFS with Memoization (DP) | O(m * n * (m+n)) | O(m * n * (m+n)) | General case; avoids recomputation of states and passes typical constraints |