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 Right INPUT String s = "aabaaaacaabc" a a b a a a a c a a b c indices: 0 1 2 3 4 5 6 7 8 9 10 11 Input Values s = "aabaaaacaabc" k = 2 Total Character Counts a: 8 b: 2 c: 2 LEFT --> <-- RIGHT ALGORITHM STEPS 1 Sliding Window Inverse Find max middle substring to SKIP (not take) 2 Count Remaining Ensure: total - window >= k for each char 3 Expand Window Move right pointer, track max valid length 4 Shrink if Invalid Move left pointer when constraint violated Max Window to Skip a a b a a a a c a a b c Green = max window (4 chars) Red = chars we must take (8) Answer = 12 - 4 = 8 FINAL RESULT Characters Taken: From Left (3) a a b From Right (5) c b a a c Verification (k=2) a: 4 taken >= 2 OK b: 2 taken >= 2 OK c: 2 taken >= 2 OK OUTPUT 8 Minimum minutes = 8 3 from left + 5 from right Key Insight: Instead of choosing from left/right, find the LONGEST MIDDLE SUBSTRING we can SKIP while still having at least k of each character in the remaining (left + right) portion. Answer = n - maxWindowLen. TutorialsPoint - Take K of Each Character From Left and Right | Sliding Window (Optimal Solution)
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