Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:
Find the leftmost occurrence of the substring part and remove it from s.
Return s after removing all occurrences of part.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "daabcbaabcbc", part = "abc"
Output: "dab"
Explanation: The following operations are done:
- s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc".
- s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc".
- s = "dababc", remove "abc" starting at index 3, so s = "dab".
Now s has no occurrences of "abc".
Example 2:
Input: s = "axxxxyyyyb", part = "xy"
Output: "ab"
Explanation: The following operations are done:
- s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb".
- s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb".
- s = "axxyyb", remove "xy" starting at index 2 so s = "axyb".
- s = "axyb", remove "xy" starting at index 1 so s = "ab".
Now s has no occurrences of "xy".
Constraints:
1 <= s.length <= 1000
1 <= part.length <= 1000
s and part consists of lowercase English letters.
Problem summary: Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: Find the leftmost occurrence of the substring part and remove it from s. Return s after removing all occurrences of part. A substring is a contiguous sequence of characters in a string.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Stack
Example 1
"daabcbaabcbc"
"abc"
Example 2
"axxxxyyyyb"
"xy"
Related Problems
Maximum Deletions on a String (maximum-deletions-on-a-string)
Step 02
Core Insight
What unlocks the optimal approach
Note that a new occurrence of pattern can appear if you remove an old one, For example, s = "ababcc" and pattern = "abc".
You can maintain a stack of characters and if the last character of the pattern size in the stack match the pattern remove them
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1910: Remove All Occurrences of a Substring
class Solution {
public String removeOccurrences(String s, String part) {
while (s.contains(part)) {
s = s.replaceFirst(part, "");
}
return s;
}
}
// Accepted solution for LeetCode #1910: Remove All Occurrences of a Substring
func removeOccurrences(s string, part string) string {
for strings.Contains(s, part) {
s = strings.Replace(s, part, "", 1)
}
return s
}
# Accepted solution for LeetCode #1910: Remove All Occurrences of a Substring
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
while part in s:
s = s.replace(part, '', 1)
return s
// Accepted solution for LeetCode #1910: Remove All Occurrences of a Substring
/**
* [1910] Remove All Occurrences of a Substring
*
* Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:
*
* Find the leftmost occurrence of the substring part and remove it from s.
*
* Return s after removing all occurrences of part.
* A substring is a contiguous sequence of characters in a string.
*
* Example 1:
*
* Input: s = "daabcbaabcbc", part = "abc"
* Output: "dab"
* Explanation: The following operations are done:
* - s = "da<u>abc</u>baabcbc", remove "abc" starting at index 2, so s = "dabaabcbc".
* - s = "daba<u>abc</u>bc", remove "abc" starting at index 4, so s = "dababc".
* - s = "dab<u>abc</u>", remove "abc" starting at index 3, so s = "dab".
* Now s has no occurrences of "abc".
*
* Example 2:
*
* Input: s = "axxxxyyyyb", part = "xy"
* Output: "ab"
* Explanation: The following operations are done:
* - s = "axxx<u>xy</u>yyyb", remove "xy" starting at index 4 so s = "axxxyyyb".
* - s = "axx<u>xy</u>yyb", remove "xy" starting at index 3 so s = "axxyyb".
* - s = "ax<u>xy</u>yb", remove "xy" starting at index 2 so s = "axyb".
* - s = "a<u>xy</u>b", remove "xy" starting at index 1 so s = "ab".
* Now s has no occurrences of "xy".
*
*
* Constraints:
*
* 1 <= s.length <= 1000
* 1 <= part.length <= 1000
* s and part consists of lowercase English letters.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/remove-all-occurrences-of-a-substring/
// discuss: https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn remove_occurrences(s: String, part: String) -> String {
s.chars()
.fold(vec![], |mut stack, c| {
stack.push(c);
if stack.len() < part.len() {
return stack;
}
if part
.chars()
.zip(stack.iter().skip(stack.len() - part.len()))
.all(|(i1, i2)| i1 == *i2)
{
stack = stack
.iter()
.take(stack.len() - part.len())
.map(|c| *c)
.collect::<Vec<_>>();
}
stack
})
.into_iter()
.collect::<_>()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1910_example_1() {
let s = "daabcbaabcbc".to_string();
let part = "abc".to_string();
let result = "dab".to_string();
assert_eq!(Solution::remove_occurrences(s, part), result);
}
#[test]
fn test_1910_example_2() {
let s = "axxxxyyyyb".to_string();
let part = "xy".to_string();
let result = "ab".to_string();
assert_eq!(Solution::remove_occurrences(s, part), result);
}
}
// Accepted solution for LeetCode #1910: Remove All Occurrences of a Substring
function removeOccurrences(s: string, part: string): string {
while (s.includes(part)) {
s = s.replace(part, '');
}
return s;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
MONOTONIC STACK
O(n) time
O(n) space
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Shortcut: Each element pushed once + popped once → O(n) amortized. The inner while-loop does not make it O(n²).
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Breaking monotonic invariant
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.