#1898

Maximum Number of Removable Characters

Medium
ArrayTwo PointersStringBinary SearchBinary SearchTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log m)
Space
O(1)
O(m)
💡

Intuition

Time O(n log m)Space O(m)

We can use binary search to find the maximum k efficiently. For each mid value in our binary search, we will check if p is a subsequence of s after removing the first mid indices in removable.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize left to 0 and right to the length of removable.
  2. 2Step 2: While left is less than or equal to right, calculate mid as (left + right) // 2.
  3. 3Step 3: Check if p is a subsequence of s after removing the first mid indices in removable.
  4. 4Step 4: If it is, update max_k to mid and move left to mid + 1. Otherwise, move right to mid - 1.
solution.py21 lines
1def is_subsequence(s, p, removable, k):
2    removed = set(removable[:k])
3    j = 0
4    for i in range(len(s)):
5        if i in removed:
6            continue
7        if j < len(p) and s[i] == p[j]:
8            j += 1
9    return j == len(p)
10
11def max_removable_characters(s, p, removable):
12    left, right = 0, len(removable)
13    max_k = 0
14    while left <= right:
15        mid = (left + right) // 2
16        if is_subsequence(s, p, removable, mid):
17            max_k = mid
18            left = mid + 1
19        else:
20            right = mid - 1
21    return max_k

Complexity note: The time complexity is O(n log m) because we perform a binary search on the range of removable indices (m) and for each mid, we check if p is a subsequence of s, which takes O(n) time.

  • 1Binary search allows us to efficiently find the maximum k.
  • 2Checking for subsequence can be done in linear time.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.