Remove All Occurrences of a Substring
Medium
Topics
Repeat the following until s no longer contains t: find the leftmost occurrence of t in s and delete it. Return the resulting string.
LeetCode names the second argument part; the harness here calls it t. It is the substring being removed.
Example 1
abc from this string takes 3 rounds and leaves dab. Only the leftmost occurrence goes at a time, and deleting it closes the gap so characters that were apart become neighbours — which can spell a fresh occurrence that was never in the original string. That is why one sweep is not enough.Input: s = "daabcbaabcbc", t = "abc" Output: "dab" Explanation: Removing the leftmost "abc" three times in turn leaves "dab". Each removal can create a new occurrence from the characters that close up.
Example 2
Input: s = "axxxxyyyyb", t = "xy" Output: "ab" Explanation: Each removal brings a new x next to a new y, so the whole middle unwinds.
Example 3
Input: s = "aaa", t = "b" Output: "aaa" Explanation: No occurrence, so nothing changes.
Constraints
- 1 <= s.length <= 1000
- 1 <= t.length <= 1000
- s and t consist of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls
Intuition
The rule that makes this interesting is that a deletion closes a gap, and the characters that become adjacent can form a new occurrence that did not exist before. So a single sweep that removes every occurrence it can see is not enough, as "axxxxyyyyb" shows: one pass removes the middle xy and leaves xy pairs that were not there to begin with.
Repeatedly searching from the start and deleting works and is easy to be confident in. Each deletion shortens the string, so the loop terminates, and the cost is bounded by the length over the part length, times the search.
A single pass is possible if you build the answer rather than edit the input. Push characters one at a time onto a growing result; after each push, check whether the tail of the result now equals t, and if so remove it. Because only the tail can be newly completed by the character just added, this check is sufficient.
That tail check is the whole insight: a new occurrence can only end at the character you just appended, so there is nowhere else to look.
Approach
- Simple version: while
toccurs ins, find the index of its first occurrence and cut those characters out. Returnswhen the search fails. - Single-pass version: start with an empty result. For each character of
s, append it. - If the result is now at least as long as
tand its lastlen(t)characters equalt, delete those characters. - Return the result once the input is exhausted.
- Comparing the tail by character rather than by building a substring avoids copying on every step.
Walkthrough
s = "daabcbaabcbc", t = "abc"
repeated leftmost deletion
d a a b c b a a b c b c indices 0..11
^ ^ ^ leftmost "abc" at 2..4
remove it, and the two sides close up
d a b a a b c b c indices 0..8
^ ^ ^ leftmost "abc" at 4..6
remove
d a b a b c indices 0..5
^ ^ ^ leftmost "abc" at 3..5
remove
d a b no occurrence left
answer "dab"
Notice the third occurrence: the "a" at index 3 and the
"b" at index 4 were not adjacent in the original string.
Closing the gap is what brought them together, which is
why one sweep is not enough.
single pass with a tail check on "axxxxyyyyb", t = "xy"
a -> "a"
x -> "ax"
x -> "axx"
x -> "axxx"
x -> "axxxx"
y -> "axxxxy", tail is "xy" -> drop -> "axxx"
y -> "axxxy", tail is "xy" -> drop -> "axx"
y -> "axxy", tail is "xy" -> drop -> "ax"
y -> "axy", tail is "xy" -> drop -> "a"
b -> "ab"
answer "ab"Complexity
- Time — O(n * m): each of the n characters triggers at most one tail comparison of length m.
- Space — O(n): the result being built.
Common Pitfalls
- Removing every occurrence in one sweep and stopping. Deletions create new occurrences, so the process has to repeat.
- Using a global replace-all. That removes the occurrences present in the original string only, and in the wrong groupings.
- Checking the whole result for occurrences after each push rather than just the tail, which is correct but turns a linear walk into a quadratic one.
- Rebuilding a substring for the tail comparison on every character. Compare in place instead.
- Assuming
tappears at all. When it does not, the answer issunchanged.
Full Solution — all languages
class Solution:
def removeOccurrences(self, s, t):
out = []
n = len(t)
for ch in s:
out.append(ch)
# A new occurrence can only END at the character just appended,
# so the tail is the only place worth checking.
if len(out) >= n and "".join(out[-n:]) == t:
del out[-n:]
return "".join(out)import java.util.*;
class Solution {
public String removeOccurrences(String s, String t) {
StringBuilder out = new StringBuilder();
int n = t.length();
for (int i = 0; i < s.length(); i++) {
out.append(s.charAt(i));
if (out.length() >= n && out.indexOf(t, out.length() - n) == out.length() - n) {
out.setLength(out.length() - n);
}
}
return out.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string removeOccurrences(string s, string t) {
string out;
int n = (int)t.size();
for (char ch : s) {
out += ch;
if ((int)out.size() >= n && out.compare(out.size() - n, n, t) == 0) {
out.erase(out.size() - n);
}
}
return out;
}
};/**
* @param {string} s
* @param {string} t
* @return {string}
*/ var removeOccurrences = function(s, t) {
const out = [];
const n = t.length;
for (const ch of s) {
out.push(ch);
if (out.length >= n) {
let same = true;
for (let i = 0; i < n; i++) {
if (out[out.length - n + i] !== t[i]) {
same = false;
break;
}
}
if (same) out.length -= n;
}
}
return out.join("");
};