Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created February 11, 2025 22:03
Show Gist options
  • Save Ifihan/9d6cceb63dd99dd864a5238a93144d4e to your computer and use it in GitHub Desktop.
Save Ifihan/9d6cceb63dd99dd864a5238a93144d4e to your computer and use it in GitHub Desktop.
Remove All Occurrences of a Substring

Question

Approach

I start by using a while loop to check if the substring part exists in s. As long as part is present, I keep removing the first occurrence of it using s.replace(part, "", 1). This ensures that I only remove one instance at a time, starting from the left. I repeat this process until part no longer appears in s. Once all instances are removed, I return the modified string.

Implementation

class Solution:
    def removeOccurrences(self, s: str, part: str) -> str:
        while part in s:
            s = s.replace(part, "", 1)
        return s

Complexities

  • Time: O(n^2)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment