Take K of Each Character From Left and Right - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "aabaaaacaabc", k = 2
›
Output:
8
💡 Note:
We need at least 2 of each character. Take "aaba" from left (4 chars) and "aabc" from right (4 chars). Total = 8 minutes.
Example 2 — Impossible Case
$
Input:
s = "a", k = 1
›
Output:
-1
💡 Note:
The string only contains 'a' but we need at least 1 'b' and 1 'c', which is impossible.
Example 3 — Zero Requirement
$
Input:
s = "abc", k = 0
›
Output:
0
💡 Note:
We need 0 of each character, so no characters need to be taken. Answer is 0.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of only characters 'a', 'b', and 'c'
- 0 ≤ k ≤ s.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with a,b,c characters and requirement k
2
Process
Take characters from left and right ends only
3
Output
Minimum minutes needed or -1 if impossible
Key Takeaway
🎯 Key Insight: Instead of minimizing what to take, maximize what to leave in the middle using sliding window
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code