Quant Memo
Coding/●●●●●

Fewest edits to balance parentheses

A user typed a filter expression using only ( and ) but got the parentheses wrong. Rather than reject it, your editor offers to auto-repair it by inserting the minimum number of parentheses (either kind, anywhere) so the string becomes valid.

"())"    -> 1     # add one '(' :  "(())"
"((("    -> 3     # add three ')'
"()"     -> 0
")("     -> 2     # add '(' at front and ')' at end

Return the minimum number of parentheses to insert to make the string valid. Aim for O(n)O(n).

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions