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
Take K of Each Character From Left and RightInput: s = "aabaaaacaabc", k = 2aabaaaaacaabcTake from LEFT4 characters: a=3, b=1, c=0Take from RIGHT4 characters: a=1, b=1, c=2Total collected: a=4≥2 ✓, b=2≥2 ✓, c=2≥2 ✓Output: 8 minutes (4 left + 4 right)
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
Asked in
Google 15 Amazon 12 Microsoft 8
28.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen