Given correct bracket sequence of no solution.
Examples
Input: ()(())
Output: ()()()
Input: ()()()
Output: no solution
expand section 🔻🔺
-
Find the rightmost opening bracket (at position
$i$ ) which we could close (replace with the closing) without loosing correctness of the sequence. In other words, we try to preserve the largest possible prefix unchanged. -
Form the lexicographically minimal bracket sequence from the remaining brackets (from
$i + 1$ position till the end of the string). Such minimal sequence can be formed by using opening brackets as much as we can (actually, half of the remainder), and then putting closing counterparts. -
Return the result sequence.
-
Return
no solutionin case we iterated over the whole sequence and didn't find possibility to make requested changes.
Complexity
Time:
Space: