Find Maximum Removals From Source String - Problem
You are given a string source of size n, a string pattern that is a subsequence of source, and a sorted integer array targetIndices that contains distinct numbers in the range [0, n - 1].
We define an operation as removing a character at an index idx from source such that:
idxis an element oftargetIndicespatternremains a subsequence ofsourceafter removing the character
Performing an operation does not change the indices of the other characters in source. For example, if you remove 'c' from "acb", the character at index 2 would still be 'b'.
Return the maximum number of operations that can be performed.
Input & Output
Example 1 — Basic Removal
$
Input:
source = "abcab", pattern = "ab", targetIndices = [1,4]
›
Output:
2
💡 Note:
We can remove characters at indices 1 and 4. After removal: source becomes "aca" → wait, this breaks the pattern. Let's recalculate: removing index 1 gives "acab", removing index 4 gives "abca". We can remove index 1 (b) to get "acab" which still contains "ab" as subsequence. We can also remove index 4 (b) to get "abca" which contains "ab". But removing both makes "aca" which doesn't contain "ab" as subsequence. So maximum is 1.
Example 2 — Multiple Options
$
Input:
source = "abbaa", pattern = "aba", targetIndices = [0,1,2]
›
Output:
1
💡 Note:
Pattern "aba" needs specific characters. We can remove at most 1 character while keeping "aba" as a subsequence.
Example 3 — No Removals Possible
$
Input:
source = "abc", pattern = "abc", targetIndices = [0,1,2]
›
Output:
0
💡 Note:
Since pattern equals source, we cannot remove any characters without breaking the pattern subsequence.
Constraints
- 1 ≤ n ≤ 3 × 103
- 1 ≤ pattern.length ≤ n
- 1 ≤ targetIndices.length ≤ n
- targetIndices is sorted in ascending order
- The characters in source and pattern are lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Given source string, pattern, and removable indices
2
Removal Strategy
Determine which characters can be safely removed
3
Pattern Check
Ensure pattern remains as subsequence after removal
Key Takeaway
🎯 Key Insight: Use DP to optimally balance character removal with pattern preservation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code