Remove All Occurrences of a Substring

Medium Stack Stack Basics

Remove All Occurrences of a Substring is a medium stack problem solved with the stack basics pattern. The best approach, optimal (stack of kmp states), runs in O(n + m) time and O(n + m) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (find and cut) up.

Problem

You are given two strings, s and part. As long as part still appears somewhere in s as a contiguous substring, find its leftmost occurrence and delete it from s, joining the pieces on either side.

Keep going until s no longer contains part, then return what is left of s (possibly the empty string).

Note that deleting one occurrence can bring letters together that form a new occurrence, and that occurrences may overlap; only the leftmost one is removed at each step.

Examples

Example 1

Input
s = "kpqpqrrk", part = "pqr"
Output
"kk"
Why
The leftmost "pqr" starts at index 3. Cutting it out leaves "kpq" + "rk" = "kpqrk", and the cut has joined a new "pqr" across the gap. Cutting that one leaves "kk", which no longer contains "pqr".

Example 2

Input
s = "ababab", part = "aba"
Output
"bab"
Why
"aba" appears at index 0 and again at index 2, overlapping the first. Only the leftmost one is removed, which leaves "bab". That string contains no "aba", so we stop.

Example 3

Input
s = "ab", part = "abc"
Output
"ab"
Why
part is longer than s, so it can never occur and s comes back unchanged.

Constraints

  • 1 <= s.length <= 1000
  • 1 <= part.length <= 1000
  • s and part contain only lowercase English letters.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 16 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (find and cut)O(n^2)O(n)
Stack with a suffix checkO(n · m)O(n)
Optimal (stack of KMP states)O(n + m)O(n + m)

1Brute force (find and cut)

TimeO(n^2)There are at most n / m cuts. Each one rebuilds the string in O(n) and searches it again, which can cost O(n · m) with a plain search, so the total is O(n / m · n · m) = O(n^2).
SpaceO(n)Each cut makes a new string of up to n characters.

Follow the statement literally. Look for the leftmost copy of part with indexOf. If there is one, build a new string from everything before it and everything after it, then search the new string again from the start. A cut can join two pieces into a fresh copy, which is why the search always restarts. Stop when indexOf finds nothing.

  1. at = s.indexOf(part).
  2. While at is not -1: s = s[0..at) + s[at + m..), then at = s.indexOf(part).
  3. Return s.
class Solution {
    public String removeOccurrences(String s, String part) {
        int at = s.indexOf(part);
        while (at != -1) {
            s = s.substring(0, at) + s.substring(at + part.length());
            at = s.indexOf(part);
        }
        return s;
    }
}

2Stack with a suffix check

TimeO(n · m)Each of the n letters is appended once, and after each append at most m letters are compared with part. Each letter is removed at most once.
SpaceO(n)The builder holds at most n letters.

Read s from left to right and keep the surviving letters in a StringBuilder used as a stack. A new copy of part can only appear at the end, right after the letter just added, so after each append compare the last m kept letters with part. If they match, cut them off by shrinking the builder. The letters left on top are exactly the ones the following letters can join with, so cascades are handled on their own, and the leftmost copy is always the first to be completed.

  1. Start with an empty builder sb; let m = part.length.
  2. For each letter c of s: append c.
  3. If sb has at least m letters and its last m letters equal part, set its length to length - m.
  4. Return sb as a string.
class Solution {
    public String removeOccurrences(String s, String part) {
        StringBuilder sb = new StringBuilder();
        int m = part.length();
        for (int i = 0; i < s.length(); i++) {
            sb.append(s.charAt(i));
            int n = sb.length();
            if (n >= m && sb.substring(n - m).equals(part)) {
                sb.setLength(n - m);
            }
        }
        return sb.toString();
    }
}

3Optimal (stack of KMP states)

TimeO(n + m)Building fail is the usual O(m). In the main loop each push raises the matched length by at most one, every fallback lowers it, and a pop leaves it at the smaller value stored underneath, so there are at most n fallbacks in total.
SpaceO(n + m)The kept letters and their states take O(n); the prefix function takes O(m).

The suffix check repeats work: it compares up to m letters after every append. The KMP prefix function fixes that. For every letter on the stack, also store k, the length of the longest prefix of part that ends at that letter. When a new letter c arrives, start from the k of the letter below it and extend it exactly as KMP does: while c does not continue the match, fall back with fail[k - 1]; if it does, add one. When k reaches m, the top m letters spell part, so pop them, and the stored k of the letter now on top is still correct, because it only describes the letters beneath it.

  1. Build fail, the KMP prefix function of part: fail[i] is the length of the longest proper prefix of part[0..i] that is also a suffix of it.
  2. Keep a char array st with a top index, and match[t] = matched length after the first t kept letters (match[0] = 0).
  3. For each letter c: k = match[top]; while k > 0 and c != part[k], k = fail[k - 1]; if c == part[k], k++.
  4. Push c and set match[top] = k. If k == m, pop m letters (top -= m).
  5. Return the first top letters of st.
class Solution {
    public String removeOccurrences(String s, String part) {
        int m = part.length(), n = s.length();
        int[] fail = new int[m];
        for (int i = 1, k = 0; i < m; i++) {
            while (k > 0 && part.charAt(i) != part.charAt(k)) k = fail[k - 1];
            if (part.charAt(i) == part.charAt(k)) k++;
            fail[i] = k;
        }
        char[] st = new char[n];
        int[] match = new int[n + 1];
        int top = 0;
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            int k = match[top];
            while (k > 0 && c != part.charAt(k)) k = fail[k - 1];
            if (c == part.charAt(k)) k++;
            st[top++] = c;
            match[top] = k;
            if (k == m) top -= m;
        }
        return new String(st, 0, top);
    }
}

Edge cases to test

  • part longer than s: nothing can be removed
  • s equal to part: the answer is the empty string
  • Removals that cascade: cutting one copy joins the pieces around it into a new copy
  • Overlapping copies such as "aba" in "ababa": only the leftmost goes, then search again
  • part of length one: every copy of that letter disappears
  • Nested copies like "aaabbb" with part "ab": everything disappears from the middle outwards
  • No copy at all: return s unchanged

Hints

Hint 1

The simplest correct program does exactly what the statement says: find the leftmost copy, cut it out, and search again from scratch.

Hint 2

Build the answer one letter at a time. After you add a letter, a new copy of part can only end at that letter. Which characters do you need to compare?

Hint 3

Treat the answer as a stack: push each letter, and whenever the top m letters spell part, pop all m of them. The letters underneath are exactly what the next letters can join with.

Hint 4

To avoid comparing m letters at every step, remember for each kept letter how much of part is matched up to it (the KMP prefix state). Popping restores the state of the letter underneath.

FAQ

What is the best time complexity for Remove All Occurrences of a Substring?

Optimal (stack of KMP states) runs in O(n + m) time and O(n + m) extra space. Building fail is the usual O(m). In the main loop each push raises the matched length by at most one, every fallback lowers it, and a pop leaves it at the smaller value stored underneath, so there are at most n fallbacks in total.

Which pattern does Remove All Occurrences of a Substring use?

It is a stack problem that uses the stack basics pattern. Other problems with the same pattern: Valid Parentheses, Baseball Game, Asteroid Collision.

Is there a brute force solution for Remove All Occurrences of a Substring?

Yes. Brute force (find and cut) takes O(n^2) time and O(n) space. Follow the statement literally.

Which edge cases should I test for Remove All Occurrences of a Substring?

part longer than s: nothing can be removed; s equal to part: the answer is the empty string; Removals that cascade: cutting one copy joins the pieces around it into a new copy; Overlapping copies such as "aba" in "ababa": only the leftmost goes, then search again; part of length one: every copy of that letter disappears; Nested copies like "aaabbb" with part "ab": everything disappears from the middle outwards; No copy at all: return s unchanged.