Remove All Occurrences of a Substring
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 <= 10001 <= part.length <= 1000sandpartcontain 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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| Brute force (find and cut) | O(n^2) | O(n) |
| Stack with a suffix check | O(n · m) | O(n) |
| Optimal (stack of KMP states) | O(n + m) | O(n + m) |
1Brute force (find and cut)
O(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).O(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.
- at = s.indexOf(part).
- While at is not -1: s = s[0..at) + s[at + m..), then at = s.indexOf(part).
- 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;
}
}class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
at = s.find(part)
while at != -1:
s = s[:at] + s[at + len(part):]
at = s.find(part)
return sclass Solution {
public:
string removeOccurrences(string s, string part) {
size_t at = s.find(part);
while (at != string::npos) {
s = s.substr(0, at) + s.substr(at + part.size());
at = s.find(part);
}
return s;
}
};class Solution {
removeOccurrences(s, part) {
let 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
O(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.O(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.
- Start with an empty builder sb; let m = part.length.
- For each letter c of s: append c.
- If sb has at least m letters and its last m letters equal part, set its length to length - m.
- 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();
}
}class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
st = []
m = len(part)
for ch in s:
st.append(ch)
n = len(st)
if n >= m and ''.join(st[n - m:]) == part:
del st[n - m:]
return ''.join(st)class Solution {
public:
string removeOccurrences(string s, string part) {
string sb;
int m = part.size();
for (int i = 0; i < (int) s.size(); i++) {
sb.push_back(s[i]);
int n = sb.size();
if (n >= m && sb.compare(n - m, m, part) == 0) {
sb.resize(n - m);
}
}
return sb;
}
};class Solution {
removeOccurrences(s, part) {
const st = [];
const m = part.length;
for (let i = 0; i < s.length; i++) {
st.push(s[i]);
const n = st.length;
if (n >= m && st.slice(n - m).join('') === part) {
st.length = n - m;
}
}
return st.join('');
}
}3Optimal (stack of KMP states)
O(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.O(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.
- 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.
- Keep a char array st with a top index, and match[t] = matched length after the first t kept letters (match[0] = 0).
- For each letter c: k = match[top]; while k > 0 and c != part[k], k = fail[k - 1]; if c == part[k], k++.
- Push c and set match[top] = k. If k == m, pop m letters (top -= m).
- 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);
}
}class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
m, n = len(part), len(s)
fail = [0] * m
k = 0
for i in range(1, m):
while k > 0 and part[i] != part[k]:
k = fail[k - 1]
if part[i] == part[k]:
k += 1
fail[i] = k
st = [''] * n
match = [0] * (n + 1)
top = 0
for c in s:
k = match[top]
while k > 0 and c != part[k]:
k = fail[k - 1]
if c == part[k]:
k += 1
st[top] = c
top += 1
match[top] = k
if k == m:
top -= m
return ''.join(st[:top])class Solution {
public:
string removeOccurrences(string s, string part) {
int m = part.size(), n = s.size();
vector<int> fail(m, 0);
for (int i = 1, k = 0; i < m; i++) {
while (k > 0 && part[i] != part[k]) k = fail[k - 1];
if (part[i] == part[k]) k++;
fail[i] = k;
}
string st(n, ' ');
vector<int> match(n + 1, 0);
int top = 0;
for (int i = 0; i < n; i++) {
char c = s[i];
int k = match[top];
while (k > 0 && c != part[k]) k = fail[k - 1];
if (c == part[k]) k++;
st[top++] = c;
match[top] = k;
if (k == m) top -= m;
}
return st.substr(0, top);
}
};class Solution {
removeOccurrences(s, part) {
const m = part.length, n = s.length;
const fail = new Array(m).fill(0);
for (let i = 1, k = 0; i < m; i++) {
while (k > 0 && part[i] !== part[k]) k = fail[k - 1];
if (part[i] === part[k]) k++;
fail[i] = k;
}
const st = new Array(n);
const match = new Array(n + 1).fill(0);
let top = 0;
for (let i = 0; i < n; i++) {
const c = s[i];
let k = match[top];
while (k > 0 && c !== part[k]) k = fail[k - 1];
if (c === part[k]) k++;
st[top++] = c;
match[top] = k;
if (k === m) top -= m;
}
return st.slice(0, top).join('');
}
}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.