NeetCode #252LC-2516MediumSliding Window
← Back to All Problems#252 · #2516 · Take K of Each Character From Left and Right(每种字符至少取 K 个)
📌 Problem Statement & Constraints
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 one character from either the left or the right end. Return the minimum number of minutes to take at least k of each character, or -1 if impossible. Constraints: 1 <= s.length <= 2 * 10^5, 0 <= k <= s.length.💡 Core Algorithmic Approaches
- Taking from both ends leaves a contiguous middle segment untouched. So the task is to find the longest middle segment that can be left behind, i.e. one where each character still has at least
koccurrences remaining outside it. - Equivalently, for a window
[l, r], the condition istotal[ch] - window_count[ch] >= kfor every character. - Slide the window to maximise its length subject to that condition.
- The answer is
n - (longest such window). If any character occurs fewer thanktimes overall, the answer is -1.
💻 Benchmark Python3 Implementation
class Solution:
def takeCharacters(self, s: str, k: int) -> int:
from collections import Counter
total = Counter(s)
for ch in "abc":
if total[ch] < k:
return -1 # impossible
cnt = Counter()
l = 0
best = 0
for r, ch in enumerate(s):
cnt[ch] += 1
# the window may be removed only if enough remains outside it
while total["a"] - cnt["a"] < k or total["b"] - cnt["b"] < k or total["c"] - cnt["c"] < k:
cnt[s[l]] -= 1
l += 1
best = max(best, r - l + 1)
return len(s) - best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): the window scan is linear.
💾 Space Complexity
O(1): two fixed-size counters.
⚠️ Interview Pitfalls & Follow-ups
- Greedily taking from the ends: the optimal strategy is not greedy -- it corresponds to leaving the longest removable middle segment.
- Checking only the character of the entering element: the condition involves all three characters, so all three must be checked.
- Forgetting the impossibility check: if some character occurs fewer than
ktimes, the answer is -1. - Returning
best: the answer is the number of characters taken, which isn - best.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Sliding Window Problems
#219 · #219Contains Duplicate II#220 · #121Best Time to Buy and Sell Stock#221 · #2379Minimum Recolors to Get K Consecutive Black Blocks#222 · #1984Minimum Difference Between Highest and Lowest of K Scores#223 · #1343Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold#224 · #1052Grumpy Bookstore Owner
中文速览与面试要点
每种字符至少取 K 个
给你一个由字符 a 、 b 、 c 组成的字符串 s 和一个非负整数 k。每分钟,你可以选择取走 s 最左侧的那个字符,或者取走最右侧的那个字符。你必须取走每种字符 至少 k 个,返回需要的 最少 分钟数。如果无法取到,则返回 −1。约束:1 ≤ s.length ≤ 2 × 10^5;s 仅由 a 、 b 、 c 组成;0 ≤ k ≤ s.length。
核心要点
- 转化为「保留最长的中间子数组」(关键洞察) :取走两端若干字符等价于「保留中间一段连续子数组」。要使取走的时间最少,就要使保留的中间段 最长 ,且保留后剩余(即被取走的)各字符数量 ≥ k。
- 剩余需求 :设字符 c 的总数为 total[c] ,则中间段中 c 的数量不能超过 total[c] − k 。
- 滑动窗口 :维护中间窗口,当某个字符的数量超过其上限时收缩左边界。答案 = n − 最长合法窗口长度 。
- 无解判定 :若某个字符的总数 < k,则无法取到 k 个,返回 −1。
常见陷阱
- 直接贪心「优先取数量最紧的那一侧」 :两侧的选择相互影响,贪心不一定最优。必须转化为「最长中间子数组」。
- 上限公式写反 :中间窗口内 c 的数量上限是 total[c] − k (因为被取走的部分需要 ≥ k)。
- 忘记无解判定 :某字符总数 < k 时直接返回 −1。
- 收缩条件写成 >= :上限是「不超过」,应写 > 。
参考实现
from collections import Counter, defaultdict
class Solution:
def takeCharacters(self, s: str, k: int) -> int:
total = Counter(s)
if any(total[c] < k for c in 'abc'):
return -1 # 某种字符总数不足
# 中间窗口内每种字符的数量上限
limit = {c: total[c] - k for c in 'abc'}
cnt = defaultdict(int)
l = 0
best = 0
for r, c in enumerate(s):
cnt[c] += 1
# 超过上限 -> 收缩
while any(cnt[ch] > limit[ch] for ch in 'abc'):
cnt[s[l]] -= 1
l += 1
if r - l + 1 > best:
best = r - l + 1
return len(s) - best