Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Minimum Number of Swaps to Make the String Balanced

XPChallenge Points: 20
levelLevel: Medium

You are given a string s of even length, made up of equal numbers of [ and ].
The goal is to make the string balanced, meaning it follows valid bracket pairing rules.

You are allowed to swap any two characters in the string.
Your task is to determine the minimum number of swaps needed to make the entire string balanced.

A string is considered balanced if:

  • It is empty, or

  • It can be formed by joining two balanced strings, or

  • It can be formed by placing a balanced string inside brackets like this: [ C ].

Example 1:

Input: s = "[]][[]"

Output: 1

Explanation:

Only one swap is required to correct the imbalance.

Example 2:

Input: s = "[][][][]"

Output: 0

Explanation:

Already balanced; no swaps required.

Example 3:

Input: s = "][[]"

Output: 1

Explanation:

Swap positions 0 and 1 → "[][]" which is balanced.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result