Find the fewest swaps that balance a string of square brackets
Company: ServiceNow
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Find the minimum number of swaps, between any two positions, that turn an even-length string of square brackets into a balanced one. It tests reasoning about prefix balances, a lower-bound argument on what a single swap can change, and a one-pass constant-space count.
Constraints
- n == len(s)
- 2 <= n <= 10^6
- n is even.
- Each s[i] is '[' or ']'.
- s contains exactly n / 2 characters '[' and n / 2 characters ']'.
Examples
Input: ('[]',)
Expected Output: 0
Explanation: Smallest valid input (length 2), already balanced.
Input: ('][',)
Expected Output: 1
Explanation: Smallest unbalanced input: maximum deficit 1 still needs one swap, so floor rounding fails.
Hints
- Scan s from left to right and compare how many `]` and `[` each prefix holds. What does a prefix with more `]` than `[` tell you about the string?
- A swap exchanges one character inside a prefix with one character outside it. By how much can a single swap change the gap between the two counts in that prefix?
- Work small cases such as `][`, `]][[` and `]]][[[` by hand and look for a pattern in the answers.