Remove All Occurrences of a Substring - Problem
You're given a string 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
Stack-Based Pattern Removal VisualizationInput Processing: "daabcbaabcbc" removing "abc"Characters to process:d a a b c b a a b c b cStack Evolution:After 'd':dAfter 'a','a':daaAfter 'b','c':dabcโ† "abc" detected!Remove "abc":dโ† Continue with remaining charsKey Algorithm Steps:1. For each character c in string: โ€ข Push c onto stack โ€ข If stack.length โ‰ฅ part.length: โ—ฆ Check last part.length chars โ—ฆ If they form 'part', pop them all2. Return stack contents as stringComplexity Analysis:Time: O(n) - each char visited onceSpace: O(n) - stack storageMuch better than brute force O(nยฒ)!Final Result: "daabcb"
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!
Asked in
Amazon 45 Google 32 Microsoft 28 Meta 24
52.2K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen