1910. Remove All Occurrences of a Substring

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.

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.

Approach 01:

class Solution {
  public:
    string removeOccurrences(string inputStr, string targetStr) {
        while (true) {
            size_t index = inputStr.find(targetStr);
            if (index != string::npos) {
                inputStr.erase(index, targetStr.length());
            } else {
                break;
            }
        }
        return inputStr;
    }
};
class Solution:
    def removeOccurrences(self, inputStr: str, targetStr: str) -> str:
        while True:
            if targetStr in inputStr:
                index = inputStr.index(targetStr)
                inputStr = inputStr[:index] + inputStr[index + len(targetStr):]
            else:
                break
        return inputStr

Time Complexity:

  • Finding the Substring:

    Each call to find() takes \( O(N) \) in the worst case, where \( N \) is the length of inputStr.

  • Erasing the Substring:

    Each call to erase() takes \( O(N) \) in the worst case, as it shifts all characters after the removed portion.

  • Loop Execution:

    In the worst case, the loop runs \( O(N / M) \) times, where \( M \) is the length of targetStr.

  • Overall Time Complexity:

    \( O(N^2 / M) \), considering multiple find() and erase() operations.

Space Complexity:

  • String Storage:

    The function operates in-place on inputStr, using \( O(1) \) extra space.

  • Overall Space Complexity:

    \( O(1) \), as no additional data structures are used.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top