Remove All Occurrences of a Substring (LeetCode 1910): Solution and Explanation
Keep removing the leftmost occurrence of part from s until none is left, and return what remains. For s = "daabcbaabcbc" and part = "abc" the answer is "dab".
Intuition
The obvious approach searches for part, deletes it and searches again. That works, but every deletion rebuilds the string and restarts the search from the beginning.
A deletion only matters where the two sides meet: the letters before the cut and the letters after it can join into a new occurrence. That is the same cascade as removing adjacent duplicates, which a stack handles well.
Push letters one at a time. A new occurrence can only end at the letter just pushed, so check whether the top m letters spell part and pop them if they do. Everything under the top has already been checked, so the occurrence found on top is always the leftmost one the brute force would remove.
Approach: Stack of letters
- Create an empty stack (a list, StringBuilder or byte slice) and let
m = part.length. - For each letter of
s, push it onto the stack. - If the stack has at least
mletters and its topmletters equalpart, pop thosemletters. - After the scan, join the stack: that is the answer.
Step-by-step example
s = "daabcbaabcbc", part = "abc"
- Push d, a, a, b, c. The top three are "abc", so cut them. Stack: "da".
- Push b, a, a, b, c. The top three are "abc" again, cut. Stack: "daba".
- Push b, c. The top three are "abc" (the a was left from before), cut. Stack: "dab".
- The scan is done. The answer is "dab".
Code: Python, Java, C++
1class Solution:
2 def removeOccurrences(self, s: str, part: str) -> str:
3 stack = []
4 m = len(part)
5 for ch in s:
6 stack.append(ch)
7 if len(stack) >= m and ''.join(stack[-m:]) == part:
8 del stack[-m:]
9 return ''.join(stack)1class Solution {
2 public String removeOccurrences(String s, String part) {
3 StringBuilder stack = new StringBuilder();
4 int m = part.length();
5 for (char ch : s.toCharArray()) {
6 stack.append(ch);
7 if (stack.length() >= m && stack.substring(stack.length() - m).equals(part)) {
8 stack.setLength(stack.length() - m);
9 }
10 }
11 return stack.toString();
12 }
13}1class Solution {
2public:
3 string removeOccurrences(string s, string part) {
4 string st;
5 int m = part.size();
6 for (char ch : s) {
7 st.push_back(ch);
8 if ((int)st.size() >= m && st.compare(st.size() - m, m, part) == 0) {
9 st.resize(st.size() - m);
10 }
11 }
12 return st;
13 }
14};Time and space complexity
O(n * m)
Each of the n pushes compares at most m letters on top. Every letter is popped at most once.
O(n)
The stack holds at most n letters.
Other approaches
Repeated find and delete (time O(n^2 / m * m) = O(n^2), space O(n))
While part appears in s, remove its first occurrence with a string replace. Short to write, but each removal copies the string and restarts the search.
Stack with KMP states (time O(n + m), space O(n + m))
Store the KMP match length alongside each pushed letter. After a pop, the state of the new top tells you how much of part is already matched, so each push costs amortised O(1) and the total is O(n + m).
Common mistakes
- Replacing every occurrence at once (
replaceAll) and stopping. A removal can create a new occurrence, so one pass of replaceAll is not enough. - Only checking the top when the pushed letter equals the last letter of
partand then comparing the wrong window. Compare exactly the topmletters. - Forgetting that
partcan be longer thans. The length check before comparing handles it.
Frequently asked questions
Why does removing at the top match removing the leftmost occurrence?
Every letter below the top has already been checked and no occurrence ended there. So the first occurrence to complete while scanning left to right is the one ending at the newest letter, which is exactly the leftmost occurrence the problem asks you to remove.
Can I do better than O(n * m)?
Yes. Keep the KMP prefix-function state for each pushed letter. Then each push is amortised O(1) and a pop restores the old state for free, giving O(n + m). For n and m up to 1000 the simple version is fast enough.
How is this related to Remove All Adjacent Duplicates?
It is the same pattern. In that problem the thing to cut is two equal letters, here it is a fixed word. In both, a cut can join the neighbours, and the stack catches that chain reaction in one pass.