DDSA Solutions

3223. Minimum Length of String After Operations

Time: O(n)
Space: O(26)
Advertisement

Intuition

Minimum string length after removing specific patterns AB and CD repeatedly. Stack simulation.

Algorithm

  1. 1Stack. For each char: if stack.top and (top+char) in {AB, CD}: pop. Else push.

Common Pitfalls

  • Stack handles nested and chained removals. Same as LC 2696 but with different patterns.
3223.cs
C#
// Approach: For each char if frequency ≥ 3 we can reduce; count final length from frequency parities.
// Time: O(n) Space: O(26)

public class Solution
{
    public int MinimumLength(string s)
    {
        int ans = 0;
        int[] count = new int[26];

        foreach (char c in s)
        {
            count[c - 'a']++;
        }

        for (int i = 0; i < 26; i++)
        {
            if (count[i] > 0)
                ans += count[i] % 2 == 0 ? 2 : 1;
        }

        return ans;
    }
}
Advertisement
Was this solution helpful?