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 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 <= 105
s
consists of only the letters'a'
,'b'
, and'c'
.0 <= k <= s.length
Solutions
Solution 1: Sliding Window
First, we use a hash table or an array of length $3$, denoted as $cnt$, to count the number of each character in string $s$. If any character appears less than $k$ times, it cannot be obtained, so we return $-1$ in advance.
The problem asks us to remove characters from the left and right sides of the string, so that the number of each remaining character is not less than $k$. We can consider the problem in reverse: remove a substring of certain size in the middle, so that in the remaining string on both sides, the number of each character is not less than $k$.
Therefore, we maintain a sliding window, with pointers $j$ and $i$ representing the left and right boundaries of the window, respectively. The string within the window is what we want to remove. Each time we move the right boundary $i$, we add the corresponding character $s[i]$ to the window (i.e., remove one character $s[i]$). If the count of $cnt[s[i]]$ is less than $k$, then we move the left boundary $j$ in a loop until the count of $cnt[s[i]]$ is not less than $k$. The size of the window at this time is $i - j + 1$, and we update the maximum window size.
The final answer is the length of string $s$ minus the size of the maximum window.
The time complexity is $O(n)$, where $n$ is the length of string $s$. The space complexity is $O(1)$.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|