Find minimum bracket reversals to balance a string of curly braces.
Problem Statement
Examples
Input: s = "}{{}}{{"
Output: 2
Explanation: Combining the input according to Minimum number of bracket reversals to make an expression balanced logic yields 2.
Input: s = "{{{"
Output: -1
Explanation: Combining the input according to Minimum number of bracket reversals to make an expression balanced logic yields -1.
Input: s = "}{"
Output: 2
Explanation: Combining the input according to Minimum number of bracket reversals to make an expression balanced logic yields 2.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
Any balanced pair {} can be greedily removed. What remains after eliminating balanced pairs will always have the form }}}...{{{ (unmatched closing followed by unmatched opening). Reversing every two adjacent same-direction brackets balances them; if both have an odd residue, two reversals balance the remaining pair.
Step-by-Step Approach
- If
s.length % 2 !== 0, return-1. - Initialize
open = 0andclose = 0. - For each character
cins: - If
c === "{", incrementopen++. - Else if
open > 0, decrementopen--(balanced pair). - Else increment
close++. - Return
Math.ceil(open / 2) + Math.ceil(close / 2).
Optimal Implementation (JavaScript)
function countBracketReversals(s) {
if (s.length % 2 !== 0) return -1;
let open = 0, close = 0;
for (let c of s) {
if (c === '{') {
open++;
} else {
if (open > 0) open--;
else close++;
}
}
return Math.ceil(open / 2) + Math.ceil(close / 2);
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Odd length: returns -1 immediately.
- Already balanced string: returns 0.
- Completely inverted string "}{": returns 2.