Skip to content

Practice Minimum Number of Swaps to Make the String Balanced

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#1963
LeetCode Problem

Minimum Number of Swaps to Make the String Balanced

Problem Statement

s has equal counts of [ and ]. Swap characters at any two indices to make its brackets balanced: each closing bracket matches an earlier opening bracket, with none unmatched. Return the minimum swaps; the swapped positions need not be adjacent.

Source: Minimum Number of Swaps to Make the String Balanced on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
s = "][]["
Output
1

# Example 2

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

# Example 3

Input
s = "[]"
Output
0

Constraints

n == s.length
2 <= n <= 10^6
n is even.
s[i] is either '[' or ']'.
The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.

Related LeetCode Problems

Practice more problems similar to Minimum Number of Swaps to Make the String Balanced.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.