Take K of Each Character From Left and Right Problem
Description
LeetCode Problem 2516.
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:
1 <= s.length <= 10^5sconsists of only the letters'a','b', and'c'.0 <= k <= s.length
Solution
Approach: Sliding Window
If any of a, b, c occurs fewer than k times in total, return -1.
Otherwise think in reverse: the characters we do not take form a contiguous middle window, and what remains outside it must still hold at least k of each letter. So find the longest window such that removing it leaves every count at least k. Extend the right end i (removing s[i] from the counts), and while cnt[s[i]] < k, shrink from the left, giving characters back. The answer is len(s) minus the longest window.
Complexity: O(n) time and O(1) space.
class Solution:
def takeCharacters(self, s: str, k: int) -> int:
cnt = Counter(s)
if any(cnt[c] < k for c in "abc"):
return -1
mx = j = 0
for i, c in enumerate(s):
cnt[c] -= 1
while cnt[c] < k:
cnt[s[j]] += 1
j += 1
mx = max(mx, i - j + 1)
return len(s) - mx