← DiffPush

Minimum Add to Make Parentheses Valid

Standard Bar Strings Hard · Hard O(n) · O(1)

The Signal Bracket Balancer

A telemetry parser rejects any packet whose bracket pattern is unbalanced — every opener needs a later closer, and no closer may arrive unpaired. Patching firmware per packet is expensive, so the gateway instead counts the fewest single brackets to splice in anywhere to legitimize the stream.

Input: A string s containing only '(' and ')'.

Output: Return the minimum number of bracket insertions needed to make s valid.

Constraints

Examples

Example 1

Input: {"s":"())"}
Output: 1
One insertion fixes the trailing closer: "(())" or "()()".

Example 2

Input: {"s":"((("}
Output: 3
Each unmatched opener needs its own closing bracket.

Solve this in your browser →

Also on LeetCode ↗