Maximum Number of Removable Characters - Problem

You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed).

You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence.

Return the maximum k you can choose such that p is still a subsequence of s after the removals.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcacb", p = "ab", removable = [3,1,0]
Output: 2
💡 Note: After removing indices 3 and 1: s becomes "a_c_cb" → "accb", which still contains "ab" as subsequence
Example 2 — Single Character
$ Input: s = "abcbddddd", p = "abcd", removable = [3,2,1,4,7,6]
Output: 4
💡 Note: Remove indices [3,2,1,4] to get "a___d_ddd" → "adddd", still contains "abcd" subsequence
Example 3 — No Removals Possible
$ Input: s = "abcab", p = "abc", removable = [0,1,2]
Output: 0
💡 Note: Removing any character breaks the subsequence, so maximum k = 0

Constraints

  • 1 ≤ p.length ≤ s.length ≤ 105
  • 0 ≤ removable.length < s.length
  • 0 ≤ removable[i] < s.length
  • p is a subsequence of s
  • s and p consist of lowercase English letters
  • The elements in removable are distinct

Visualization

Tap to expand
Maximum Removable Characters ProblemInput:s = "abcacb"p = "ab"removable = [3,1,0]abcacb012345Binary Search on k:k=0: Remove [] → "abcacb" has "ab" ✓k=1: Remove [3] → "abc_cb" has "ab" ✓k=2: Remove [3,1] → "a_c_cb" has "ab" ✗Maximum k = 1Can remove 1 character while preserving subsequence "ab"
Understanding the Visualization
1
Input
String s, target subsequence p, and removable indices
2
Binary Search
Find maximum k where p remains subsequence after removing k characters
3
Output
Return the maximum valid k
Key Takeaway
🎯 Key Insight: Use binary search on the answer since the problem has monotonic property - if k works, all smaller values work too
Asked in
Google 15 Facebook 12 Amazon 8
28.4K Views
Medium Frequency
~25 min Avg. Time
856 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