Fewest Brackets to Balance
A string of brackets is balanced when every ( is closed by a ) that comes after it, and every ) closes a ( that came before it. You may add brackets anywhere in the string brackets. Return the fewest brackets you need to add to make it balanced.
Examples
brackets = "())" → 1
brackets = "(((" → 3
brackets = "()()" → 0
brackets = ")((" → 3In the first example one ( at the start gives "(())". In the last, the ) needs a ( before it, and each ( needs a ) after it.
Constraints
- Between 0 and 20,000 characters, each
(or). - Aim for O(n) time and O(1) memory.
Console
›Run to see what your code prints
Run checks the 4 visible cases here, in your browser. Submit runs all 8 on the judge, 4 of them hidden, and measures how your solution scales.
Expected is the reference solution's answer, from the judge. An input that breaks the statement's other rules may get any answer.