Take K of Each Character From Left and Right - Problem
Take K of Each Character From Left and Right
You're given a string
The Challenge: Each minute, you can remove either the leftmost or rightmost character from the string. Your goal is to collect at least
Return the minimum minutes needed, or
Example: For string
You're given a string
s containing only the characters 'a', 'b', and 'c', along with a non-negative integer k. The Challenge: Each minute, you can remove either the leftmost or rightmost character from the string. Your goal is to collect at least
k of each character ('a', 'b', and 'c') in the minimum number of minutes possible.Return the minimum minutes needed, or
-1 if it's impossible to collect k of each character.Example: For string
"aabaaaacaaac" and k = 2, you need at least 2 'a's, 2 'b's, and 2 'c's. By taking characters from both ends strategically, you can achieve this in 8 minutes. Input & Output
example_1.py โ Basic Case
$
Input:
s = "aabaaaacaaac", k = 2
โบ
Output:
8
๐ก Note:
We need at least 2 'a's, 2 'b's, and 2 'c's. Take 3 characters from left ('a', 'a', 'b') and 5 from right ('a', 'a', 'a', 'c', 'c'). This gives us 5 'a's, 1 'b', and 2 'c's from left+right combined, but we only took 1 'b' from left, so we need to adjust. Optimal: take 8 characters total.
example_2.py โ Edge Case
$
Input:
s = "a", k = 1
โบ
Output:
-1
๐ก Note:
The string only contains 'a' but we need at least 1 of each character ('a', 'b', 'c'). Since there are no 'b' or 'c' characters, it's impossible.
example_3.py โ Zero Requirement
$
Input:
s = "abc", k = 0
โบ
Output:
0
๐ก Note:
We need 0 of each character, so we don't need to take any characters. Return 0 minutes.
Constraints
- 1 โค s.length โค 105
- s consists of only characters 'a', 'b', and 'c'
- 0 โค k โค s.length
- The string may not contain all three characters
Visualization
Tap to expand
Understanding the Visualization
1
Count Total
First, count total characters and verify if solution exists
2
Sliding Window
Use window to represent middle section we want to leave
3
Expand & Check
Expand window right, check if remaining chars satisfy k requirement
4
Shrink if Invalid
If invalid, shrink window from left until valid
5
Track Maximum
Keep track of maximum valid window size found
Key Takeaway
๐ฏ Key Insight: Transform the problem from 'minimize characters taken' to 'maximize characters left in middle' using sliding window technique!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code