Split the Binary string into two substring with equal 0’s and 1’s
Pattern: Strings basics and frequency
Keep a balance, +1 for a 0 and -1 for a 1. Every time it returns to 0, a balanced piece has ended, so cut there. Cutting as early as possible gives the most pieces.
The problem
You are given a string of 0s and 1s. Split it into the largest number of pieces, in order and covering the whole
string, so that every piece has equally many 0s and 1s. Return that number, or -1 if it cannot be done. For example,
"0100110101" gives 4 (01, 0011, 01, 01), and "0000000000" gives -1.
The link above is a GeeksforGeeks article. The function name maxSubStr is this guide's own.
Think first
- When is the whole split impossible?
- Walking left to right, how can you tell that the piece you are in is balanced so far?
- Is it ever better to wait instead of cutting at the first balanced point?
Hints
Brute force, and why it fails
Try every set of cut points and keep the best valid one: exponential. A DP over cut positions is O(n²). The balance scan is O(n).
The key insight
Each time the running balance returns to 0, the part since the last cut is balanced. Every such point is a safe cut, so the answer is simply how many times the balance hits 0.
Dry run
| balance | 0 |
|---|---|
| pieces | 0 |
str = 0100110101. The balance starts at 0.
The plan
balance = 0, pieces = 0
for each c in str:
if c == '0': balance = balance + 1 else balance = balance - 1
if balance == 0: pieces = pieces + 1
return pieces if balance == 0 else -1
Complexity
- Time
O(n)- Space
O(1)
One pass with two counters.
Edge cases
- All one digit: -1.
"01"or"10": 1."1100110"has seven characters and an odd count, so -1.
I've built my logic, show the code
Java
class Solution {
public int maxSubStr(String str) {
int balance = 0, pieces = 0; // balance = 0s seen minus 1s seen
for (int i = 0; i < str.length(); i++) {
balance += str.charAt(i) == '0' ? 1 : -1;
if (balance == 0) pieces++; // the piece ending here is balanced: cut
}
return balance == 0 ? pieces : -1; // the whole string must be balanced too
}
}C++
class Solution {
public:
int maxSubStr(string str) {
int balance = 0, pieces = 0; // balance = 0s seen minus 1s seen
for (char c : str) {
balance += c == '0' ? 1 : -1;
if (balance == 0) pieces++; // the piece ending here is balanced: cut
}
return balance == 0 ? pieces : -1; // the whole string must be balanced too
}
};Python
class Solution:
def maxSubStr(self, str_: str) -> int:
balance = pieces = 0 # balance = 0s seen minus 1s seen
for c in str_:
balance += 1 if c == "0" else -1
if balance == 0:
pieces += 1 # the piece ending here is balanced: cut
return pieces if balance == 0 else -1 # the whole string must be balanced tooCommon mistakes
- Forgetting the final check, so an unbalanced tail still returns a count.
- Resetting the balance at each cut. It is already 0 there.
- Counting pairs of neighbours instead of balance returns.