DDSA Solutions

1963. Minimum Number of Swaps to Make the String Balanced

Time: O(n)
Space: O(1)

Problem Overview

Minimum Number of Swaps to Make the String Balanced (Unknown) asks you to solve a structured algorithmic task. This is a common Two Pointers / String pattern in coding interviews. Count unmatched ']' after cancelling matched pairs; answer = ceil(unmatched / 2).

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Count unmatched ']' after cancelling matched pairs; answer = ceil(unmatched / 2).

Related patterns: Two Pointers, String, Greedy

1963.cs
C#
// Approach: Count unmatched ']' after cancelling matched pairs; answer = ceil(unmatched / 2).
// Time: O(n) Space: O(1)

public class Solution
{
    public int MinSwaps(string s)
    {
        // Cancel out all the matched pairs, then we'll be left with "]]]..[[[".
        // The answer is ceil(the number of unmatched pairs / 2).
        int unmatched = 0;

        foreach (char c in s)
        {
            if (c == '[')
            {
                unmatched++;
            }
            else if (unmatched > 0)
            { // c == ']' and there's a match.
                unmatched--;
            }
        }

        return (unmatched + 1) / 2;
    }
}
Was this solution helpful?

Related Problems