↓Skip to main content
  1. LeetCode/

LeetCode 2516: Take K of Each Character From Left and Right

·2 mins· ·
LeetCode Medium Sliding-Window Hash-Table String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-01-11

  • Submissions: Wrong Answer → Runtime Error ×2 → Accepted

Approach
#

As in LeetCode 1423, taking from both ends = leaving a contiguous middle block.

Taking at least k of each letter ⇔ the middle keeps at most total − k of each. So:

  1. Compute each letter’s limit limit[c] = count[c] - k. If any is < 0, the total is not enough: return -1.
  2. Find the longest middle block with a “longest” sliding window: shrink the left when the newly added letter goes over its limit.
  3. The answer is n - longest length.

My Attempts
#

All the mistakes were in step 1:

VersionProblem
Attempt 1, WAWrote char not in freq or freq[char] < k. With k = 0 nothing is needed, but a letter absent from the string was still judged short. For s = "b", k = 0, the answer is 0; this returned -1
Attempts 2–3, RESwitched to and (attempt 3 also added k > 0), so a letter present but short no longer returned -1; its limit went negative, no window was ever valid, and left ran off the string. For s = "abc", k = 2, it raised IndexError; the answer is -1
AC(k > 0 and char not in freq) or freq[char] < k

Checking count[c] - k < 0 alone is enough: Counter returns 0 for missing letters, and with k = 0, 0 - 0 is not negative.

Solution
#

class Solution:
    def takeCharacters(self, s: str, k: int) -> int:
        limit = Counter(s)
        for c in "abc":
            limit[c] -= k                          # how many c the middle may keep
            if limit[c] < 0:
                return -1

        cnt = Counter()
        left = best = 0
        for right, c in enumerate(s):
            cnt[c] += 1
            while cnt[c] > limit[c]:
                cnt[s[left]] -= 1
                left += 1
            best = max(best, right - left + 1)
        return len(s) - best

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • With k = 0, no letters are needed.
  • Return early when a total is short; otherwise the limit is negative and the window loop runs out of range.

Interview Explanation
#

Taking from both ends leaves a contiguous middle, so I flip the problem: the middle may keep at most total minus k of each letter, and the answer is the length minus the longest such middle. If a total is short I return -1 right away. A longest-window slide shrinks the left when the new letter exceeds its limit. Time O(n).

Related

LeetCode 1016: Binary String With Substrings Representing 1 To N
·3 mins
LeetCode Medium Sliding-Window String Bit-Manipulation Hash-Table
LeetCode 1016 note: s has at most 1000 characters, so there are few substrings of any fixed length and a large n must be False; checking from n downward fails fast, or extend up to 30 bits from each start to collect every value <= n
LeetCode 3694: Distinct Points Reachable After Substring Removal
·2 mins
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table String
LeetCode 3694 note: the endpoint is the total displacement minus the removed segment’s displacement; a length-k window tracks that segment and each endpoint goes into a set
LeetCode 187: Repeated DNA Sequences
·1 min
LeetCode Medium Hash-Table String Bit-Manipulation Sliding-Window
LeetCode 187 note: count every length-10 substring in a hash map and return those seen more than once
LeetCode 424: Longest Repeating Character Replacement
·2 mins
LeetCode Medium Hash-Table String Sliding-Window
LeetCode 424 note: a variable sliding window where window length minus the top character count is the number of replacements; shrink when it exceeds k
LeetCode 2831: Find the Longest Equal Subarray
·2 mins
LeetCode Medium Sliding-Window Hash-Table Binary-Search Array
LeetCode 2831 note: list the positions of each value and slide a window over that list; the deletions needed are the span of positions minus the number of copies
LeetCode 1461: Check If a String Contains All Binary Codes of Size K
·2 mins
LeetCode Medium Hash-Table String Bit-Manipulation Rolling-Hash
LeetCode 1461 note: put every length-k substring in a set and check that its size reaches 2^k; the last start is len(s) - k