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 of a Substring INPUT String s: d a a b c b a a b c b c Pattern part: a b c Input Values: s = "daabcbaabcbc" part = "abc" Remove all "abc" from s from left to right ALGORITHM STEPS 1 Find leftmost "abc" Search s for pattern da[abc]baabcbc 2 Remove occurrence Delete "abc" substring da~~baabcbc --> "dabaabcbc" 3 Repeat until done Loop while part exists Iterations: 1: daabcbaabcbc -abc 2: dabaabcbc -abc 3: dababc -abc 4: dab (DONE) 4 Return result No more "abc" found FINAL RESULT Original string: d a a b c b a a b c b c Final string: d a b Output: "dab" OK - All "abc" removed 3 iterations completed Key Insight: The optimal approach uses a simple loop with string's built-in find() and replace() or erase() methods. Time complexity is O(n * m) where n is string length and m is pattern length. After each removal, we restart the search from the beginning to catch newly formed occurrences of the pattern. TutorialsPoint - Remove All Occurrences of a Substring | Optimal Solution
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