2516. Take K of Each Character From Left and Right

Difficulty:
Related Topics:
Similar Questions:

Problem

You are given a string s consisting of the characters 'a', 'b', and 'c' and a non-negative integer k. Each minute, you may take either the leftmost character of s, or the rightmost character of s.

Return** the minimum number of minutes needed for you to take at least k of each character, or return -1 if it is not possible to take k of each character.**

  Example 1:

Input: s = "aabaaaacaabc", k = 2
Output: 8
Explanation: 
Take three characters from the left of s. You now have two 'a' characters, and one 'b' character.
Take five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters.
A total of 3 + 5 = 8 minutes is needed.
It can be proven that 8 is the minimum number of minutes needed.

Example 2:

Input: s = "a", k = 1
Output: -1
Explanation: It is not possible to take one 'b' or 'c' so return -1.

  Constraints:

Solution (Java)

class Solution {
    public int takeCharacters(String s, int k) {

        if(k == 0) return 0;

        int n = s.length();
        int req = k * 3;

         s = s + s;

        int[] f = new int[3];

        for(int i = 0 ; i < n ; i++) {

            char ch = s.charAt(i);
            f[ch - 'a']++;
        }

        int ans = Integer.MAX_VALUE;
        int j = 0;

        while(j < n) {

            if(check(f, k)) {
                f[s.charAt(j) - 'a']--;

                ans = n - j;
                j++;

            }
            else break;
        }

        for(int i = n ; i < s.length() ; i++) {

            if(j > n) break;
            if(i - n >= j) break;

            f[s.charAt(i) - 'a']++;

            while(j < i) {

                if(check(f, k)) {
                    f[s.charAt(j) - 'a']--;

                    ans = Math.min(i - j + 1, ans);
                    j++;

                }
                else break;

                if(j > n) break;
                if(i - n >= j) break;
            }
        }

        if(ans == Integer.MAX_VALUE) return -1;

        return ans;
    }

    boolean check(int[] a,int k) {

        for(int ele : a) {

            if(ele < k) return false;
        }

        return true;
    }
}

Explain:

nope.

Complexity: