Magicsheet logo

Take K of Each Character From Left and Right

Medium
12.5%
Updated 8/1/2025

Take K of Each Character From Left and Right

What is this problem about?

In the Take K of Each Character From Left and Right interview question, you are given a string s consisting of characters 'a', 'b', and 'c', and an integer k. You can take characters from either the left or the right end of the string. Your goal is to find the minimum number of minutes (one minute per character) required to take at least k of each character. If it's impossible, return -1.

Why is this asked in interviews?

This "Medium" difficulty problem is popular at Meta and Amazon because it tests your ability to transform a "taking from ends" problem into a sliding window problem. It evaluates your skills in string analysis and optimization. Instead of simulating the removal from both ends, a more efficient approach is to find the longest "middle" part of the string that can be left behind while still satisfying the k requirement for each character.

Algorithmic pattern used

The primary pattern is the Sliding Window interview pattern.

  1. Count the total occurrences of 'a', 'b', and 'c' in the string. If any count is less than k, return -1.
  2. The problem then becomes: find the maximum length of a contiguous subarray (window) such that if we remove this window, the remaining characters (the ones we "took") contain at least k of 'a', 'b', and 'c'.
  3. This is equivalent to finding a window where the frequency of each character inside is count - k or less.
  4. Use a sliding window to find this maximum length, and the answer will be total_length - max_window_length.

Example explanation

String: aabaaaacaabc, k = 2.

  • Total counts: a=8, b=2, c=2.
  • We need to keep at least 2 of each.
  • Max 'a' we can "leave behind" in a window is 8 - 2 = 6.
  • Max 'b' we can leave behind is 2 - 2 = 0.
  • Max 'c' we can leave behind is 2 - 2 = 0. We look for the longest window that has no 'b's and no 'c's and at most 6 'a's. In our string, aaaa is a valid window. If we leave that, we took everything else.

Common mistakes candidates make

A common error is trying to use a greedy approach (taking characters from whichever side seems "better" at the moment), which doesn't always lead to the global minimum. Another mistake is forgetting to handle the case where the entire string is not enough to satisfy the k requirement. Some candidates also struggle with the window conditions—specifically, how to define the "limit" for each character inside the window.

Interview preparation tip

To excel in the Take K of Each Character From Left and Right coding problem, practice converting "two-ended" removal problems into "middle" window problems. This is a very common trick in competitive programming. Mastery of the Sliding Window interview pattern is essential for reducing O(n²) or O(2^n) search problems to linear O(n) solutions.

Similar Questions