Remove All Occurrences of a Substring - Problem
You're given a string
Your task is to repeatedly find the leftmost occurrence of
Example: If
Return the final string after all possible removals.
s and a substring part that you need to completely eliminate from s. Here's the catch: removing one occurrence might create new occurrences!Your task is to repeatedly find the leftmost occurrence of
part in s and remove it, until no more occurrences exist. Think of it like a chain reaction where each removal might expose new patterns.Example: If
s = "daabcbaabcbc" and part = "abc", removing the first "abc" gives us "daabcbabc", but now there's still another "abc" to remove!Return the final string after all possible removals.
Input & Output
example_1.py โ Basic Removal
$
Input:
s = "daabcbaabcbc", part = "abc"
โบ
Output:
"daabcb"
๐ก Note:
Remove first "abc" โ "daabcbabc". Remove second "abc" โ "daabcb". No more "abc" patterns exist.
example_2.py โ Chain Reaction
$
Input:
s = "abccba", part = "ab"
โบ
Output:
"cccba"
๐ก Note:
Remove "ab" from position 0 โ "ccba". No more "ab" patterns found, so we stop.
example_3.py โ No Occurrences
$
Input:
s = "hello", part = "xyz"
โบ
Output:
"hello"
๐ก Note:
The substring "xyz" doesn't exist in "hello", so the string remains unchanged.
Constraints
- 1 โค s.length โค 1000
- 1 โค part.length โค 1000
- s and part consist of lowercase English letters
- s contains at least one occurrence of part initially
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Stack
Start with an empty stack to build our result
2
Process Each Character
Add characters one by one to the stack
3
Pattern Detection
After each addition, check if top forms unwanted pattern
4
Immediate Removal
Remove pattern immediately when detected
5
Final Result
Stack contents form the final cleaned string
Key Takeaway
๐ฏ Key Insight: Using a stack allows us to detect and remove patterns immediately as we build the string, handling chain reactions efficiently in a single pass!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code