( can be matched with a later closing bracket ) so that the pairs nest properly and no bracket is left unmatched. The empty string is balanced too.
You are given a string seq made of ( and ). In one step you may insert a single bracket of either kind anywhere in the string.
Return the minimum number of insertions that make seq balanced.seq=')(()' → 2
The inner () is already matched. The leading ) lacks an opener and the ( at index 1 lacks a closer, so two brackets are needed, e.g. ()(()).
seq='(())()' → 0
The sequence is already balanced, so nothing has to be added.
seq='))' → 2
Both closing brackets need a partner, so two ( go in front.
seq.length ≤ 1000seq[i] is ( or )seq=')(()'
2
Run checks the first 3 tests in your browser. Submit checks all 117 tests on the server, hidden ones included.