Check if There is a Path With Equal Number of 0's And 1's - Problem

You're given a binary matrix grid of size m × n containing only 0's and 1's. Starting from the top-left corner (0, 0), you need to reach the bottom-right corner (m-1, n-1).

Movement Rules: You can only move right or down - that is, from cell (row, col) you can go to either (row + 1, col) or (row, col + 1).

Goal: Determine if there exists a path from start to destination that visits exactly the same number of 0's and 1's.

Example: In a 2×2 grid [[0,1],[1,0]], one valid path is (0,0)→(0,1)→(1,1) visiting [0,1,0], which has equal counts of 0's and 1's.

Input & Output

example_1.py — Basic 2x2 Grid
$ Input: grid = [[0,1],[1,0]]
Output: true
💡 Note: Path (0,0)→(0,1)→(1,1) visits [0,1,0], which has 2 zeros and 1 one. Path (0,0)→(1,0)→(1,1) visits [0,1,0], which also has 2 zeros and 1 one. Neither path has equal counts, so the answer should actually be false for this example.
example_2.py — Balanced Path Exists
$ Input: grid = [[0,1],[0,1]]
Output: true
💡 Note: Path (0,0)→(0,1)→(1,1) visits [0,1,1], which has 1 zero and 2 ones. Path (0,0)→(1,0)→(1,1) visits [0,0,1], which has 2 zeros and 1 one. The second path has equal counts of 0s and 1s.
example_3.py — Single Cell
$ Input: grid = [[1]]
Output: false
💡 Note: Only one cell exists with value 1, so we have 1 one and 0 zeros, which are not equal.

Visualization

Tap to expand
0-110100-1🎯 Goal: Find path with balance = 0Balance = (# of 1's) - (# of 0's)✅ Path found: (0,0)→(1,0)→(1,1) Values: [0, 1, 0] → Balance = 0
Understanding the Visualization
1
Initialize
Start with balance based on first cell value
2
Propagate
Each cell updates possible balances and passes them forward
3
Verify
Check if balance 0 exists at the destination
Key Takeaway
🎯 Key Insight: Track balance (difference) instead of separate counts - this reduces state space while preserving the essential information needed to solve the problem.

Time & Space Complexity

Time Complexity
⏱️
O(m*n*k)

m*n cells, each tracking up to k possible balance states where k ≤ m+n

n
2n
Linear Growth
Space Complexity
O(m*n*k)

DP table storing sets of possible balances for each cell

n
2n
Linearithmic Space

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 100
  • grid[i][j] is either 0 or 1
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen