Taro Logo

Remove All Occurrences of a Substring

#127 Most AskedMedium
Topics:
StringsTwo Pointers

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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the maximum lengths of strings `s` and `part`?
  2. Can `part` be longer than `s`, and what should I return in that case?
  3. Should the removal process be case-sensitive?
  4. Could the removal of one occurrence of `part` inadvertently create a new instance of `part` that needs to be removed next?
  5. What character set do `s` and `part` consist of (e.g., standard ASCII, lowercase English letters only, or Unicode)?

Brute Force Solution

Approach

Imagine you have a long string of text and you want to completely erase a specific smaller word or pattern hidden inside it. The brute force approach repeatedly scans the main text from start to finish, looking for that hidden pattern, and chops it out whenever it appears.

Here's how the algorithm would work step-by-step:

  1. Look at the main text from the very beginning to see if the target pattern appears anywhere inside it.
  2. If you spot the pattern, remove that exact occurrence completely, which will cause the remaining parts of the text to shift together and close the gap.
  3. Since removing one piece might accidentally cause the surrounding letters to form a brand new copy of the pattern, you cannot just stop yet.
  4. Start your search over from the beginning of the newly formed text to check for any remaining copies of the pattern.
  5. Repeat this entire process of searching and removing over and over again.
  6. Finally stop when you scan the entire text from start to finish and find zero copies of the pattern left anywhere inside.

Code Implementation

def remove_occurrences(main_string, target_pattern):
    # We repeatedly loop because removing a pattern can create new instances of the pattern
    while target_pattern in main_string:
        
        pattern_index = main_string.find(target_pattern)
        
        # Slicing is necessary to cleanly excise the target while preserving the rest of the text
        main_string = main_string[:pattern_index] + main_string[pattern_index + len(target_pattern):]
        
    return main_string

Big(O) Analysis

Time Complexity
O(n^2) – Let n be the length of the main string and m be the length of the target pattern. In the worst case, we might need to remove the pattern up to n/2 times, and each search and removal operation takes proportional to the current length of the string, which is bounded by n. This leads to a series of operations proportional to n plus (n-m) plus (n-2m) and so on, approximating n times n/2 work overall. Simplifying this by dropping constants results in a final Big O time complexity of O(n^2).
Space Complexity
O(n) – The simulation of repeatedly removing the target pattern requires building and storing newly formed strings in memory as the text shifts and closes gaps. In the worst-case scenario where no removals happen initially or the string shrinks gradually, temporary string objects can grow proportional to the input size N. Additionally, programming languages often store intermediate string states during these continuous search-and-remove operations. Thus, the auxiliary space complexity scales linearly with respect to the input size N.

Optimal Solution

Approach

To remove all copies of a specific target word from a main message, we can process the text from start to finish while constantly checking our work. Whenever the target word accidentally forms at the end of what we have processed so far, we simply wipe it away before moving forward.

Here's how the algorithm would work step-by-step:

  1. Begin scanning the main message from the very beginning, letter by letter.
  2. Keep a running collection of the letters you have examined so far.
  3. Every time you add a new letter to your collection, check if the forbidden target word has just appeared at the very end.
  4. If you spot the target word at the end of your collection, immediately delete those specific letters.
  5. Continue adding letters from the main message, repeating the deletion check every single time a new letter joins.
  6. Once you reach the very end of the main message, your running collection will be completely free of any hidden copies of the target word.

Code Implementation

def remove_occurrences(main_message: str, target_word: str) -> str:
    running_collection = []
    target_length = len(target_word)

    for current_letter in main_message:
        running_collection.append(current_letter)

        # We check the end of our collection to catch the forbidden word immediately.
        if len(running_collection) >= target_length and ''.join(running_collection[-target_length:]) == target_word:
            
            # Deleting the matched suffix prevents cascading instances from being missed.
            del running_collection[-target_length:]

    # Joining the remaining letters ensures no hidden copies of the target word remain.
    return ''.join(running_collection)

Big(O) Analysis

Time Complexity
O(n * m) – As we scan through the main message of length n character by character, each new character is appended to our running collection and potentially checked for the matching target word of length m. In the worst-case scenario where the target word repeatedly appears and is deleted, slicing the end of the collection takes proportional time to the length of the target word. This substring comparison and removal operation happens for each of the n characters in the message. Therefore, the total operations approximate to n times m, which simplifies to the Big O time complexity of O(n * m).
Space Complexity
O(n) – The auxiliary data structure driving the space complexity is the running collection of letters, which acts as a dynamic builder. In the worst-case scenario where no occurrences of the target word are found, this collection stores all characters from the main message. As the input size N grows, the extra memory required scales linearly to hold up to N characters. Therefore, the auxiliary space complexity simplifies to Big O of N.

Edge Cases

The part string is longer than the source string s
How to Handle:
The algorithm naturally finds no match and returns the original string unchanged.
The source string s is empty
How to Handle:
The loop condition fails immediately and returns an empty string.
Removing a part creates a new instance of part in the resulting string
How to Handle:
Repeatedly searching from the beginning or using a stack-based approach handles cascading removals correctly.
The part string is identical to the source string s
How to Handle:
The entire string is removed in one pass, leaving an empty result.
Maximum-sized inputs with many overlapping or repeating patterns
How to Handle:
Using a stack or StringBuilder instead of repeated string concatenation avoids quadratic time complexity.
The part string does not appear in s at all
How to Handle:
The search operation returns not found on the first attempt and returns s as-is.
0/245 completed