#3316
Find Maximum Removals From Source String
MediumArrayHash TableTwo PointersStringDynamic ProgrammingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a two-pointer technique to efficiently check how many characters can be removed while ensuring the pattern remains a subsequence. We iterate through the target indices and check if removing characters still allows the pattern to be formed.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers, one for the source string and one for the pattern.
- 2Step 2: Iterate through the targetIndices and try to remove characters from the source string.
- 3Step 3: For each character removal, check if the pattern can still be formed using the two-pointer technique.
- 4Step 4: Count the maximum number of valid removals.
solution.py21 lines
1# Full working Python code
2
3def max_removals_optimal(source, pattern, targetIndices):
4 left = 0
5 right = 0
6 max_removals = 0
7 while right < len(targetIndices):
8 # Try to remove the character at targetIndices[right]
9 removed = targetIndices[right]
10 left_ptr, pattern_ptr = 0, 0
11 while left_ptr < len(source):
12 if left_ptr == removed:
13 left_ptr += 1
14 continue
15 if pattern_ptr < len(pattern) and source[left_ptr] == pattern[pattern_ptr]:
16 pattern_ptr += 1
17 left_ptr += 1
18 if pattern_ptr == len(pattern):
19 max_removals += 1
20 right += 1
21 return max_removalsℹ
Complexity note: The time complexity is O(n) because we only iterate through the source string once for each removal attempt, making it efficient.
- 1Understanding subsequences is crucial for this problem.
- 2Using two pointers can significantly reduce time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.