DDSA
Advertisement

2516. Take K of Each Character From Left and Right

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

Approach

Sliding window on excluded middle; maximize exclusion while keeping ≥k of each char.

2516.cs
C#
// Approach: Sliding window on excluded middle; maximize exclusion while keeping ≥k of each char.
// Time: O(n) Space: O(1)

public class Solution
{
    public int TakeCharacters(string s, int k)
    {
        int n = s.Length;
        int ans = n;
        int[] count = new int[3];

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

        if (count[0] < k || count[1] < k || count[2] < k)
            return -1;

        for (int l = 0, r = 0; r < n; r++)
        {
            count[s[r] - 'a']--;
            while (count[s[r] - 'a'] < k)
            {
                count[s[l] - 'a']++;
                l++;
            }
            ans = Math.Min(ans, n - (r - l + 1));
        }

        return ans;
    }
}
Advertisement
Was this solution helpful?