Remove All Occurrences of a Substring (LeetCode 1910): Solution and Explanation

Medium
String
Stack
Simulation

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

  1. Create an empty stack (a list, StringBuilder or byte slice) and let m = part.length.
  2. For each letter of s, push it onto the stack.
  3. If the stack has at least m letters and its top m letters equal part, pop those m letters.
  4. After the scan, join the stack: that is the answer.

Step-by-step example

s = "daabcbaabcbc", part = "abc"
  1. Push d, a, a, b, c. The top three are "abc", so cut them. Stack: "da".
  2. Push b, a, a, b, c. The top three are "abc" again, cut. Stack: "daba".
  3. Push b, c. The top three are "abc" (the a was left from before), cut. Stack: "dab".
  4. 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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n * m)

Each of the n pushes compares at most m letters on top. Every letter is popped at most once.

Space

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 part and then comparing the wrong window. Compare exactly the top m letters.
  • Forgetting that part can be longer than s. 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.