In this coding problem, you are given an binary matrix. You start at the top-left corner and want to reach the bottom-right corner . You can only move down or right. A path is valid if the number of 0s is exactly equal to the number of 1s in that path.
Google asks this to test your proficiency with Dynamic Programming and Matrix traversal. It’s a variation of the "unique paths" problem but with an added constraint. It evaluates whether you can identify the necessary state to track (the "balance" of 0s and 1s) and whether you can optimize that state using properties of the grid (like the fixed path length).
This is a Dynamic Programming (DP) on a Matrix problem. The path length from to is always . For the number of 0s to equal the number of 1s, this total length must be even (which means must be odd). The DP state dp[i][j] could store a set of possible "balances" (number of 1s minus number of 0s) that can be reached at cell . If 0 is in the set at the bottom-right cell, a valid path exists.
Matrix : 1 1 0 0 0 1 Path length: .
A common error is not realizing that the total path length must be even for an equal count to be possible. Another is using a simple boolean DP that only tracks the best balance, which is incorrect because a "lesser" balance might be the only one that can be corrected later. Using a bitset to store possible balances is a common optimization for this problem.
When a grid problem involves a "sum" or "count" constraint, think about what values are possible at each cell. If the range of values is small, you can store all possible outcomes in a set or a bitmask at each DP state.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Bomb Enemy | Medium | Solve | |
| Longest Line of Consecutive One in Matrix | Medium | Solve | |
| Minimum Path Cost in a Grid | Medium | Solve | |
| Maximum Non Negative Product in a Matrix | Medium | Solve | |
| Maximum Number of Moves in a Grid | Medium | Solve |