You are given a string of unknown length that contains a varied amount of (
, {
, [
and their respective closing parentheses (in this context all referred to as brackets).
With one exception, all the brackets are all balanced, meaning an opening one has a corresponding closing one somewhere afterwards in the string.
The brackets may not be "interpolated" with each other, i.e. opening bracket b which is inside opening bracket a must close before bracket a closes, so ([)]
, {[(]})
, and ({[(])}())[()]
are invalid, but ([])
, {[()]}
, and ({[()]})()[()]
are valid.
Challenge
The task is, inside the string there is a single unbalanced bracket, i.e. an opening bracket that does not have a closing one. You must insert the closing bracket where it is the farthest distance apart from the opening bracket, but not interpolated with other brackets, then return the modified (or new) string.
Test cases
^
added to point out where a bracket was added.
"(" --> "()"
^
"[(]" --> "[()]"
^
"{[({}()([[[{}]]])]{[]}}" --> "{[({}()([[[{}]]]))]{[]}}"
^
"[[[]]" --> "[[[]]]"
^
"{[[]([(()){[[{}]()]})]}" --> "{[[]([(()){[[{}]()]}])]}"
^
Scoring
This is code-golf, so shortest code wins.
Difference from "possible dupes":
- This one only wants to see if the brackets are matched; nothing else
- Quite similar, but in that question is the possibility that one must add multiple braces, which I would approach quite differently in answering