> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/two-pointer/sliding-window/2516.-take-k-of-each-character-from-left-and-right.md).

# 2516. Take K of Each Character From Left and Right

T: O(n), n is string length

S: O(3)

```java
class Solution {
    public int takeCharacters(String s, int k) {
        int n = s.length();
        int[] map = new int[3];
        for (char c : s.toCharArray()) {
            map[c - 'a']++;
        }
        for (char c : "abc".toCharArray()) {
            map[c - 'a'] -= k; // 6, 0, 0
            if (map[c - 'a'] < 0) {
                return -1;
            }
        }

        int[] currentCount = new int[3];
        int left = 0;
        int right = 0;
        int maxSize = 0;
        while (right < n) {
            char rightChar = s.charAt(right); // c
            currentCount[rightChar - 'a']++; // a: 1, b:0, c:0
            right++;
            
            while (currentCount[rightChar - 'a'] > map[rightChar - 'a'] ) { // 
                char leftChar = s.charAt(left);
                currentCount[leftChar - 'a']--;
                left++;
            }
            maxSize = Math.max(maxSize, right - left); //  r - l = 0
        }
        return n - maxSize;
    }
}a
```
