Quant Memo
Coding/●●●●●

Fewest swaps to balance brackets

You have a string of only [ and ], with an equal count of each, so a balanced arrangement is always achievable. A single swap exchanges any two characters (not necessarily adjacent).

"[]"       -> 0
"]["       -> 1     # swap the two characters
"]]][[["   -> 2
"][]["     -> 1

Return the minimum number of swaps needed to make the string balanced. 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