Fewest Insertions to Balance Parentheses

Asked at Meta · Coding Questions · Difficulty: Medium

A string made only of `(` and `)` is balanced when every `(` is matched by a later `)` and every `)` by an earlier `(`, so that no prefix has more closing than opening brackets and the totals are equal. You may insert `(` or `)` anywhere in the string. Find how few insertions make it balanced, and then produce such a repaired string.

Loading the problem…