Leetcode 1898: Maximum Number of Removable Characters

grid47
grid47
Exploring patterns and algorithms
May 1, 2024 8 min read

You are given two strings s and p, where p is a subsequence of s. You are also given an array removable containing distinct indices of s. Your task is to determine the maximum number of indices you can remove from s such that p is still a subsequence of the remaining string.
Problem
Approach
Steps
Complexity
Input: The input consists of a string s, a string p, and an array removable of distinct indices in s.
Example: For s = 'abcacb', p = 'ab', removable = [3, 1, 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 both consist of lowercase English letters.
• The elements in removable are distinct.
Output: Return the maximum number of indices you can remove from s such that p remains a subsequence.
Example: For s = 'abcacb', p = 'ab', removable = [3, 1, 0], the output will be 2.
Constraints:
• The output is an integer.
Goal: The goal is to determine the maximum number of indices that can be removed without losing the subsequence property of p in s.
Steps:
• Iterate through the array removable and remove characters from s accordingly.
• For each number of removals, check if p is still a subsequence of the remaining string.
• Use binary search to find the maximum number of removable indices where p remains a subsequence.
Goal: The input is constrained to be within certain limits.
Steps:
• The length of s can be up to 10^5, and the length of removable can be less than the length of s.
Assumptions:
• p is always a subsequence of s.
• The elements in removable are distinct and valid indices of s.
Input: s = 'abcacb', p = 'ab', removable = [3, 1, 0]
Explanation: After removing characters at indices 3 and 1, s becomes 'accb', which still contains p as a subsequence. Removing the characters at indices 3, 1, and 0 results in 'ccb', which no longer contains p.

Input: s = 'abcbddddd', p = 'abcd', removable = [3, 2, 1, 4, 5, 6]
Explanation: After removing the character at index 3, 'abcbddddd' becomes 'abcddddd', and p remains a subsequence.

Input: s = 'abcab', p = 'abc', removable = [0, 1, 2, 3, 4]
Explanation: If the first index in removable is removed, p is no longer a subsequence of the resulting string.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus