Skip to main content

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

MediumPremiumFree on FleetCodeArrayDynamic ProgrammingMatrix8 min readAsked at: Google
Practice this problem

Problem Statement

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.length
  • n == grid[i].length
  • 2 <= m, n <= 100
  • grid[i][j] is either 0 or 1.

Approach Overview

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.

Solution

According to the problem description, we know that the number of 0s and 1s on the path from the top-left corner to the bottom-right corner is equal, and the total number is m + n - 1, which means the number of 0s and 1s are both (m + n - 1) / 2.

Therefore, we can use memoization search, starting from the top-left corner and moving right or down until reaching the bottom-right corner, to check if the number of 0s and 1s on the path is equal.

The time complexity is O(m times n times (m + n)). Here, m and n are the number of rows and columns of the matrix, respectively.

Code

Python

Java

C++

Go

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force DFSO(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

Video Solution

leetcode 2510. Check if There is a Path With Equal Number of 0's And 1's - recursion+cache solution • Code-Yao • 424 views views

Watch 2 more video solutions →

Frequently Asked Questions

Is Check if There is a Path With Equal Number of 0's And 1's easy or hard?
The problem is rated Medium on LeetCode. The challenge is recognizing the parity constraint and converting the path search into a dynamic programming problem with memoization and pruning.
Check if There is a Path With Equal Number of 0's And 1's Python/Java solution
Implement a recursive DFS that tracks position and balance, treating 1 as +1 and 0 as -1. Use a memoization set or DP table to skip repeated states. The same logic translates directly across Python, Java, C++, and Go.
How to solve Check if There is a Path With Equal Number of 0's And 1's in O(n)?
An O(n) solution is not possible because the algorithm must consider multiple states across the grid. The practical optimal solution uses DFS with memoization over the matrix, leading to about O(m * n * (m+n)) complexity with pruning based on remaining steps.
What is the best approach for Check if There is a Path With Equal Number of 0's And 1's?
DFS with memoization (dynamic programming) is the most effective approach. Track the grid position and the current balance between ones and zeros, and cache visited states to avoid recomputation. This reduces the search from exponential paths to roughly O(m * n * (m+n)).
Is Check if There is a Path With Equal Number of 0's And 1's asked at Google/Amazon/Meta?
Grid dynamic programming and path constraint problems like this appear frequently in interviews at companies such as Google, Amazon, and Meta. The problem tests DFS state exploration, memoization, and pruning techniques.
What data structure is used in Check if There is a Path With Equal Number of 0's And 1's?
The main structures are a 2D matrix representing the grid and a memoization cache (often a hash set or 3D DP structure) that stores visited states defined by row, column, and balance of zeros vs ones.
What is the time complexity of Check if There is a Path With Equal Number of 0's And 1's?
The optimized solution runs in O(m * n * (m+n)) time. Each grid cell can be visited with different balance values representing the difference between counts of 1s and 0s along the path.

Ready to solve this problem?

Practice Check if There is a Path With Equal Number of 0's And 1's with our built-in code editor and test cases.

Practice on FleetCode