15% off all plans & roadmaps Use code
See plansLeetCode 1963 · Solution & editorial
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.
Minimum Number of Swaps to Make the String Balanced is a Stack Patterns problem, in the Valid Parentheses Matching subpattern. The pattern covers parentheses matching, monotonic stack, histogram, and expression evaluation
Master parentheses validation and balancing using stack. Handle multiple bracket types and minimum additions.
The reference solution runs in O(n) time and O(1) space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Minimum Number of Swaps to Make the String Balanced is a Stack Patterns problem, in the Valid Parentheses Matching subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.