Fewest Brackets to Balance

EasyStack≈ 15 min

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

text
brackets = "())"    →  1
brackets = "((("    →  3
brackets = "()()"   →  0
brackets = ")(("    →  3

In 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.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
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.