0
Leetcode Problem 1963. Minimum Number of Swaps to Make the String Balanced
1963. Minimum Number of Swaps to Make the String Balanced
AI Mock Interview
Leetcode Solutions
Greedy Approach with Balance Count
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Initialize
balance
and
swaps
to 0, and
j
to the last index of the string.
Iterate through the string with index
i
.
If the current character is an opening bracket, increment
balance
.
If it is a closing bracket, decrement
balance
.
If
balance
is negative, it means we need to swap:
Find the next opening bracket from the end of the string by decrementing
j
.
Swap the brackets at indices
i
and
j
.
Increment
swaps
and reset
balance
to 1.
Continue the process until the end of the string.
Return the
swaps
count.
Stack-Based Approach
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...