Back to Practice Dashboard
Competitive ProgrammingEasy

Minimum Swaps brackets balancing

Learn how to solve the 'Minimum Swaps brackets balancing' problem. This detailed resource details brute force and optimized approaches.

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?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

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

Open in Editor