NeetCode #289LC-1898MediumBinary Search
← Back to All Problems#289 · #1898 · Maximum Number of Removable Characters(可移除字符的最大数目)
📌 Problem Statement & Constraints
You are given strings
s and p, and an array removable of indices into s. You may remove the characters at the first k indices of removable. Return the largest k such that p is still a subsequence of the remaining string. Constraints: 1 <= p.length <= s.length <= 10^5, 0 <= removable.length < s.length; all indices are distinct.💡 Core Algorithmic Approaches
- Binary search on
k: "ispstill a subsequence after removing the firstkindices" is monotone ink. - For a given
k, mark the firstkindices as removed and run the standard two-pointer subsequence check. - Feasible when
pis fully matched. Use the upper-biased midpoint to find the largest feasiblek. - Rebuilding the removed set for each check costs O(k); using a boolean array of size
nkeeps each check O(n).
💻 Benchmark Python3 Implementation
class Solution:
def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:
n = len(s)
def feasible(k: int) -> bool:
removed = [False] * n
for i in range(k):
removed[removable[i]] = True
j = 0 # pointer into p
for i, ch in enumerate(s):
if removed[i]:
continue # character removed
if j < len(p) and ch == p[j]:
j += 1
return j == len(p)
lo, hi = 0, len(removable)
while lo < hi:
mid = (lo + hi + 1) // 2 # upper-biased: maximise k
if feasible(mid):
lo = mid
else:
hi = mid - 1
return lo⚡ Complexity Deep Dive
⏱️ Time Complexity
O((n + m) log m) where m is the number of removable indices: each feasibility check is O(n + m).
💾 Space Complexity
O(n) for the removed array.
⚠️ Interview Pitfalls & Follow-ups
- Using the lower-biased midpoint with
lo = mid: infinite loop; the upper bias is required for maximisation. - Actually deleting characters from the string: O(n) per removal and error-prone; a boolean mask is cleaner.
- Forgetting that
pmust remain a subsequence, not a substring: the two-pointer check is the right one. - Assuming
k = 0is always feasible:pmight not be a subsequence ofseven without removals; the problem guarantees it is, but the binary search handles either case.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Binary Search Problems
中文速览与面试要点
可移除字符的最大数目
给你两个字符串 s 和 p,其中 p 是 s 的一个 子序列 。另给你一个 互不相同 的整数数组 removable,其中包含 [0, s.length − 1] 范围内的整数。你想从 s 中移除一些字符(removable 中的字符),使得移除后 p 仍然是 s 的一个子序列。请返回你可以移除的 最多 字符数目。约束:1 ≤ p.length ≤ s.length ≤ 10^5;0 ≤ removable.length < s.length;0 ≤ removable[i] < s.length;p 和 s 都由小写英文字母组成;s 中的所有字符在 removable 中互不相同。
核心要点
- 二分移除数量 + 子序列判定(标准解) :二分「移除 removable 的前 k 个下标」,判定「移除后 p 是否仍是 s 的子序列」。
- 单调性(关键) :移除的字符越多,越难保持 p 是子序列。因此「移除前 k 个后仍可行」关于 k 具有单调性。
- 子序列判定 :用双指针在 s 上扫描(跳过被移除的下标),贪心匹配 p。
- 为什么可以二分 :removable 的顺序无关紧要(题目只问数量),但为了单调性,我们固定「移除前 k 个」并二分 k。
常见陷阱
- 二分模板用向下取整的 mid 配合 l = mid :会死循环。求最大值必须用 (l + r + 1) // 2 。
- 判定中用列表 i in removed :list 的成员判断是 O(k),整体退化为 O(n · k)。必须用集合。
- 误以为可以任意选择移除哪些字符 :题目要求移除的是 removable 中的字符,且我们二分的是「移除前 k 个」。由于 removable 元素互不相同且只问数量,这个二分是合理的。
- 子序列判定写成 p in s :那是子串判断,不是子序列。必须用双指针贪心匹配。
参考实现
class Solution:
def maximumRemovals(self, s: str, p: str, removable: list[int]) -> int:
def is_subsequence(removed: set) -> bool:
"""移除 removed 中的下标后,p 是否仍是 s 的子序列。"""
j = 0
for i, c in enumerate(s):
if i in removed:
continue
if j < len(p) and c == p[j]:
j += 1
return j == len(p)
l, r = 0, len(removable)
while l < r:
mid = (l + r + 1) // 2 # 向上取整,配合 l = mid
if is_subsequence(set(removable[:mid])):
l = mid # 可行 -> 尝试移除更多
else:
r = mid - 1
return l