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:

  • idx is an element of targetIndices
  • pattern remains a subsequence of source after 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 Case
$ Input: source = "abcacb", pattern = "ab", targetIndices = [3,1,0]
Output: 2
💡 Note: Remove characters at indices 3 and 1. After removal: "abcb" → pattern "ab" is still a subsequence.
Example 2 — Cannot Remove All
$ Input: source = "abcabc", pattern = "abc", targetIndices = [2,1,0]
Output: 1
💡 Note: Can only remove one character while keeping pattern "abc" as subsequence.
Example 3 — No Removals Possible
$ Input: source = "abc", pattern = "abc", targetIndices = [0,1,2]
Output: 0
💡 Note: Pattern uses all characters, so no characters can be removed.

Constraints

  • 1 ≤ source.length ≤ 3000
  • 1 ≤ pattern.length ≤ source.length
  • 1 ≤ targetIndices.length ≤ source.length
  • 0 ≤ targetIndices[i] < source.length

Visualization

Tap to expand
INPUTALGORITHMRESULTabcacbSource: "abcacb"Pattern: "ab"Targets: [3,1,0]Red boxes show target indices1Try remove index 32Check if "abccb" → "ab"3Try remove index 14Check if "accb" → "ab"Greedy removal testing2RemovalsMaximum charactersthat can be removedwhile preservingpattern subsequenceKey Insight:Greedily test each removal while ensuring the pattern remains a valid subsequence.Use dynamic programming or two pointers to efficiently validate subsequence property.TutorialsPoint - Find Maximum Removals From Source String | Dynamic Programming
Asked in
Google 15 Microsoft 12 Amazon 10
8.9K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen