Problem Description
Given a string s that consists of the characters 'a', 'b', and 'c' and an integer k, you must determine the minimum number of minutes required to pick characters from either the leftmost or rightmost side so that you accumulate at least k of each character. If it is not possible to collect k of each character, return -1.
Key Insights
- Instead of simulating left/right picks directly, consider the complementary contiguous subarray (the part that is not picked).
- The problem is equivalent to finding the longest subarray that can be left untouched such that the remaining characters (those taken from the sides) still contain at least k of each character.
- For each character ch in {'a', 'b', 'c'}, the window can contain at most (total_count[ch] - k) occurrences.
- Use a sliding window approach to find the maximum length of such a valid subarray.
Space and Time Complexity
Time Complexity: O(n) – A single pass (or two, in the worst case) through the string using the sliding window. Space Complexity: O(1) – Only constant space is required to track counts for three characters.
Solution
The solution begins by counting the total occurrences of 'a', 'b', and 'c' in the string. If any character occurs less than k times, the answer is immediately -1. Next, we use the sliding window strategy to identify the longest contiguous subarray that can remain while ensuring that for each character ch, the subarray contains at most (total_counts[ch] - k) occurrences. This guarantee makes sure that the characters removed from the boundaries (the complement of this window) sum to at least k for each character. The answer is then the length of the string minus the length of this maximum valid window.