bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1963. Minimum Number of Swaps to Make the String Balanced

1963. Minimum Number of Swaps to Make the String Balanced

Leetcode Solutions

Greedy Approach with Balance Count

  1. Initialize balance and swaps to 0, and j to the last index of the string.
  2. 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.
  3. 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.
  4. Continue the process until the end of the string.
  5. Return the swaps count.
UML Thumbnail

Stack-Based Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...