Remove All Occurrences of a Substring - Problem

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.

Input & Output

Example 1 — Basic Removal
$ Input: s = "daabcbaabcbc", part = "abc"
Output: "dab"
💡 Note: Remove first "abc" → "daabcbbc", then remove second "abc" → "dabb", then remove "bbc" doesn't contain "abc", final result is "dab"
Example 2 — Complete Removal
$ Input: s = "aabababa", part = "aba"
Output: "ba"
💡 Note: Remove "aba" from position 1 → "ababa", remove "aba" from position 0 → "ba", no more occurrences found
Example 3 — No Occurrences
$ Input: s = "hello", part = "world"
Output: "hello"
💡 Note: The substring "world" is not found in "hello", so the original string is returned unchanged

Constraints

  • 1 ≤ s.length ≤ 1000
  • 1 ≤ part.length ≤ 1000
  • s and part consist of lowercase English letters

Visualization

Tap to expand
Remove All Occurrences: "abc" from "daabcbaabcbc"d a a b c b a a b c b cOriginal stringd a a b c b a a b c b cFind and remove "abc" occurrencesd a bFinal result
Understanding the Visualization
1
Input
Original string with target substring to remove
2
Process
Remove occurrences, which may expose new ones
3
Output
Final string with all occurrences removed
Key Takeaway
🎯 Key Insight: Each removal might expose new pattern occurrences, requiring continuous checking until no more matches exist
Asked in
Facebook 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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