LeetCode 3316: Find Maximum Removals From Source String Solution
Master LeetCode problem 3316 (Find Maximum Removals From Source String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3316. Find Maximum Removals From Source String
Problem Explanation
Explanation
To solve this problem, we can iterate through the targetIndices array and for each index, we check if removing the character at that index still maintains the pattern as a subsequence of the source string. We can achieve this by using two pointers, one for the source string and one for the pattern string. If the characters at the corresponding positions match, we increment both pointers. If not, we only increment the source string pointer.
We keep track of the maximum number of removals that can be made while maintaining the pattern. The maximum number of removals possible corresponds to the minimum number of characters between two target indices that are required to maintain the pattern.
Finally, we return the maximum number of removals that can be made.
- Time complexity: O(n), where n is the length of the source string.
- Space complexity: O(1)
Solution Code
class Solution {
public int maximumRemovals(String source, String pattern, int[] targetIndices) {
int left = 0, right = targetIndices.length - 1;
int maxRemovals = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (canRemove(source, pattern, targetIndices, mid)) {
maxRemovals = mid + 1;
left = mid + 1;
} else {
right = mid - 1;
}
}
return maxRemovals;
}
private boolean canRemove(String source, String pattern, int[] targetIndices, int k) {
StringBuilder sb = new StringBuilder(source);
for (int i = 0; i <= k; i++) {
sb.setCharAt(targetIndices[i], '_');
}
int j = 0;
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == pattern.charAt(j)) {
j++;
if (j == pattern.length()) {
return true;
}
}
}
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3316 (Find Maximum Removals From Source String)?
This page provides optimized solutions for LeetCode problem 3316 (Find Maximum Removals From Source String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3316 (Find Maximum Removals From Source String)?
The time complexity for LeetCode 3316 (Find Maximum Removals From Source String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3316 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3316 in Java, C++, or Python.