Competitive ProgrammingEasy

Minimum Swaps brackets balancing

Detailed guide and Python implementation for the 'Minimum Swaps brackets balancing' problem.

Problem Statement

Easy

Write a function minimum_swaps_balancing(s) that takes a string s of square brackets [ and ] containing equal numbers of opening and closing brackets, and returns the minimum number of swaps of adjacent characters needed to balance the string.

Constraints
  • 2 <= len(s) <= 10^5
  • s contains only '[' and ']'
  • Count of '[' equals count of ']'

Examples

Example 1
Input
minimum_swaps_balancing('[]][[]')
Output
1
Explanation

Swap index 2 and 3 -> '[][][]', which is balanced. (1 swap)

Example 2
Input
minimum_swaps_balancing(']]][[[')
Output
6
Explanation

We can swap adjacent brackets to make it balanced, requiring 6 swaps in total.

Need a Hint?
Consider using Greedy-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.