Minimum Number of Swaps to Make the String Balanced

You are given a string `s` of even length `n` that contains exactly `n / 2` opening brackets `[` and `n / 2` closing brackets `]`. A string is balanced if it is empty, or is `AB` with both `A` and `B` balanced, or is `[C]` with `C` balanced. You may swap the brackets at any two indices any number of times. Return the minimum number of swaps needed to make `s` balanced.

30:00

Minimum Number of Swaps to Make the String Balanced
medium
Free written solution
Topics
Companies

You are given a string s of even length n that contains exactly n / 2 opening brackets [ and n / 2 closing brackets ]. A string is balanced if it is empty, or is AB with both A and B balanced, or is [C] with C balanced. You may swap the brackets at any two indices any number of times. Return the minimum number of swaps needed to make s balanced.

Example 1:
Input: {"s":"][]["}
Output: 1
Constraints:
  • n=s.lengthn = s.\text{length}

  • 2≤n≤1062 \leq n \leq 10^6

  • nn is even.

  • s[i] is either '[' or ']'.

  • The number of '[' equals n / 2, and the number of ']' equals n / 2.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"][]["}

s, scanned left to right: matched · [ waiting · ] stray

]

0

[

1

]

2

[

3

Scan left to right and cancel every matched [ ] pair with a stack counter. Only the brackets that never find a partner need swaps.

stack of waiting '[' (open = 0)

(empty)

unmatched brackets after cancelling pairs

none

Variables
VariableValue
open0
DepthFunction Call
Stack empty
0/5