Quick 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.

Find the fewest swaps that balance a string of square brackets

Company: ServiceNow

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

You are given a string `s` of even length `n`. It contains exactly `n / 2` opening brackets `[` and exactly `n / 2` closing brackets `]`. A string is balanced if it is empty, or it can be written as `AB` where `A` and `B` are both balanced, or it can be written as `[C]` where `C` is balanced. In one swap you exchange the brackets at any two indices, and you may swap as many times as you like. Return the minimum number of swaps needed to make `s` balanced. ### Function Signature ```python def min_swaps(s: str) -> int: ``` ### Rules - The two indices in a swap do not need to be adjacent. - The counts of `[` and `]` are equal, so some sequence of swaps always balances the string and an answer always exists. - Return `0` when `s` is already balanced. ### 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 ```text Input: s = "][][" Output: 1 ``` Swapping index 0 with index 3 gives `"[[]]"`, which is balanced. The input is not balanced, so at least one swap is needed. ```text Input: s = "]]][[[" Output: 2 ``` Swapping index 0 with index 4 gives `"[]][]["`, and then swapping index 1 with index 5 gives `"[[][]]"`. One swap cannot be enough: it changes at most one of the first three characters, so the first three characters would still hold more `]` than `[`. ```text Input: s = "[]][][" Output: 1 ``` Swapping index 2 with index 5 gives `"[][[]]"`, which is balanced. The leading `"[]"` is already matched and needs no work.

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.

You are given a string `s` of even length `n` made only of the characters `[` and `]`. It contains exactly `n / 2` opening brackets `[` and exactly `n / 2` closing brackets `]`. A string is balanced if it is empty, or it can be written as `AB` where `A` and `B` are both balanced, or it can be written as `[C]` where `C` is balanced. In one swap you choose any two indices of `s` and exchange the brackets at those indices. The two indices do not need to be adjacent, and you may make as many swaps as you like. Return the minimum number of swaps needed to make `s` balanced. Because the counts of `[` and `]` are equal, some sequence of swaps always balances the string, so an answer always exists. Return `0` when `s` is already balanced. The answer never exceeds 250,000, so a 32-bit signed integer holds it in every language. ### 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 `]`. ### Example 1 ```text Input: s = "][][" Output: 1 ``` Swapping index 0 with index 3 gives `"[[]]"`, which is balanced. The input is not balanced, so at least one swap is needed. ### Example 2 ```text Input: s = "]]][[[" Output: 2 ``` Swapping index 0 with index 4 gives `"[]][]["`, and then swapping index 1 with index 5 gives `"[[][]]"`. One swap cannot be enough: it changes at most one of the first three characters, so the first three characters would still hold more `]` than `[`.

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

  1. 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?
  2. 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?
  3. Work small cases such as `][`, `]][[` and `]]][[[` by hand and look for a pattern in the answers.

Fewest Swaps to Balance a Bracket String

mediumServiceNowSoftware Engineer

You are given a string s of even length n made only of the characters [ and ]. It contains exactly n / 2 opening brackets [ and exactly n / 2 closing brackets ].

A string is balanced if it is empty, or it can be written as AB where A and B are both balanced, or it can be written as [C] where C is balanced.

In one swap you choose any two indices of s and exchange the brackets at those indices. The two indices do not need to be adjacent, and you may make as many swaps as you like. Return the minimum number of swaps needed to make s balanced.

Because the counts of [ and ] are equal, some sequence of swaps always balances the string, so an answer always exists. Return 0 when s is already balanced. The answer never exceeds 250,000, so a 32-bit signed integer holds it in every language.

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 ].

Example 1

Input: s = "][]["
Output: 1

Swapping index 0 with index 3 gives "[[]]", which is balanced. The input is not balanced, so at least one swap is needed.

Example 2

Input: s = "]]][[["
Output: 2

Swapping index 0 with index 4 gives "[]][][", and then swapping index 1 with index 5 gives "[[][]]". One swap cannot be enough: it changes at most one of the first three characters, so the first three characters would still hold more ] than [.

Examples

Example 1
Input
('[]',)
Output
0
Notes
Smallest valid input (length 2), already balanced.
Example 2
Input
('][',)
Output
1
Notes
Smallest unbalanced input: maximum deficit 1 still needs one swap, so floor rounding fails.

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 ']'.

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def min_swaps(s) -> int:
Sample call
min_swaps('[]')
Language
Case 1
Input
('[]',)
Expected
0
Case 2
Input
('][',)
Expected
1

Browse More Questions

Show the approach

Approach

Track the deficit of each prefix: the number of ] in the prefix minus the number of [. Let M be the largest deficit over all prefixes, or 0 when no prefix has a positive deficit. The answer is ceil(M / 2), computed as (M + 1) // 2 in one left-to-right scan.

Lower bound: a balanced string has no prefix with a positive deficit. A swap exchanges at most one character inside a given prefix with one character outside it, so it changes that prefix's deficit by at most 2. The prefix whose deficit is M therefore needs at least ceil(M / 2) swaps.

Upper bound: while M > 0, let i be the first index where the deficit becomes positive and let j be the index of the last [. The total deficit is 0, so some [ follows i and j > i. Every character after j is ], so each prefix ending at or after j has deficit at most 0. Swapping positions i and j lowers the deficit of every prefix ending in [i, j - 1] by exactly 2 and leaves every other prefix unchanged. All prefixes with a positive deficit lie in that range, so the new maximum is max(0, M - 2). Repeating this reaches a string with no positive-deficit prefix after ceil(M / 2) swaps, and a string with equal counts and no positive-deficit prefix is balanced.

Edge cases: an already balanced string has M = 0 and returns 0. A single unmatched closer (M = 1) still needs one swap, which is why the result rounds up. The scan keeps two integers, so the largest input (n = 10^6) runs in one pass with constant extra memory, and the result is at most 250,000.

Time complexity:
O(n)
Space complexity:
O(1)