2516. Take K of Each Character From Left and Right
Description
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 leastk
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:
1 <= s.length <= 105
s
consists of only the letters'a'
,'b'
, and'c'
.0 <= k <= s.length
Solutions
Solution: Sliding Window
- Time complexity: O(n)
- Space complexity: O(1)
JavaScript
js
/**
* @param {string} s
* @param {number} k
* @return {number}
*/
const takeCharacters = function (s, k) {
if (k === 0) return 0;
const n = s.length;
const countMap = { a: 0, b: 0, c: 0 };
let right = 0;
let result = n;
for (const letter of s) {
countMap[letter] += 1;
}
if (countMap.a < k || countMap.b < k || countMap.c < k) return -1;
for (let index = 0; index < n; index++) {
const letter = s[index];
while (right < n && countMap[s[right]] > k) {
countMap[s[right]] -= 1;
right += 1;
}
result = Math.min(index + n - right, result);
countMap[letter] += 1;
}
return result;
};