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.
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
while part in s:
s = s.replace(part, "", 1)
return s- Time: O(n^2)
- Space: O(n)