Minimum number of bracket reversals to make an expression balanced
Pattern: Balanced brackets
Cancel every matched pair. What is left looks like ))…)((…(: c unmatched closers and o unmatched openers. Reversing one of each pair of closers (and openers) fixes two at once, so the answer is ceil(c / 2) + ceil(o / 2). An odd length cannot be fixed: -1.
The problem
Given a string of ( and ), return the fewest characters to reverse (turn ( into ) or back) so that it becomes
balanced, or -1 if that is impossible. ")(())(((" gives 3; "(()((()(())((" (odd length 13) gives -1.
Think first
- When is it impossible?
- After cancelling matched pairs, what can the leftovers look like?
- How many reversals fix
))? And)(?
Hints
Brute force, and why it fails
Try every subset of positions to reverse: O(2ⁿ × n).
The key insight
Matched pairs never need touching. In the leftovers, every two closers cost one reversal and every two openers cost one; an odd one of each costs one more each.
Dry run
| open | 0 |
|---|---|
| close | 1 |
s = ")(())(((" has even length 8. The first ) has nothing to match: close = 1.
The plan
if len(s) is odd: return -1
open = close = 0
for c in s:
if c == '(': open += 1
elif open > 0: open -= 1
else: close += 1
return ceil(open / 2) + ceil(close / 2)
Complexity
- Time
O(n)- Space
O(1)
One pass with two counters, instead of an explicit stack of leftovers.
Edge cases
- Already balanced: 0.
)(: 2.- Odd length:
-1.
I've built my logic, show the code
Java
class Solution {
public int countRev(String s) {
if (s.length() % 2 == 1) return -1; // an odd length can never balance
int open = 0, close = 0; // unmatched '(' and unmatched ')'
for (char c : s.toCharArray()) {
if (c == '(') open++;
else if (open > 0) open--; // this ')' matches an earlier '('
else close++;
}
return (open + 1) / 2 + (close + 1) / 2; // "))" or "((" needs 1 reversal, ")(" needs 2
}
}C++
class Solution {
public:
int countRev(string s) {
if (s.size() % 2 == 1) return -1; // an odd length can never balance
int open = 0, close = 0; // unmatched '(' and unmatched ')'
for (char c : s) {
if (c == '(') open++;
else if (open > 0) open--; // this ')' matches an earlier '('
else close++;
}
return (open + 1) / 2 + (close + 1) / 2; // "))" or "((" needs 1 reversal, ")(" needs 2
}
};Python
class Solution:
def countRev(self, s: str) -> int:
if len(s) % 2:
return -1 # an odd length can never balance
opened = closed = 0 # unmatched '(' and unmatched ')'
for c in s:
if c == "(":
opened += 1
elif opened:
opened -= 1 # this ')' matches an earlier '('
else:
closed += 1
return (opened + 1) // 2 + (closed + 1) // 2 # "))" or "((" needs 1 reversal, ")(" needs 2Common mistakes
- Returning
(open + close) / 2, which is wrong for)((gives 1, needs 2). - Forgetting the odd-length check.