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: false
💡 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 is false.
example_2.py — Balanced Path Exists
$ Input: grid = [[0,1],[0,1]]
Output: false
💡 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. Neither 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.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 100
  • grid[i][j] is either 0 or 1

Visualization

Tap to expand
Path with Equal 0's and 1's INPUT 0 1 1 0 START END Input Parameters: grid = [[0,1],[1,0]] m = 2, n = 2 Path length = 3 cells (odd length needed) ALGORITHM STEPS 1 Check Path Length Length = m+n-1 = 3 (odd = impossible equal) 2 Transform Values Replace 0 with -1 Sum=0 means equal count 3 DP with Sum State Track reachable sums at each cell position 4 Check Final Cell Is sum=0 reachable? at destination (m-1,n-1) Possible Paths: Path 1: 0-->1-->0 = (-1,1,-1) Sum = -1 (not equal) Path 2: 0-->1-->0 = (-1,1,-1) Sum = -1 (not equal) FINAL RESULT 0 1 1 0 Output: true Verification: Path: (0,0)-->(1,0)-->(1,1) Values: 0, 1, 0 Count: two 0's, one 1 Wait... checking both paths Key Insight: Transform 0's to -1's. A path has equal 0's and 1's if and only if the path sum equals 0. Use DP to track all possible sums reachable at each cell. Path length must be even for equal count. Time: O(m*n*(m+n)) | Space: O(m*n*(m+n)) using set-based DP at each position. TutorialsPoint - Check if There is a Path With Equal Number of 0's And 1's | Optimal Solution
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