Remove All Occurrences of a Substring — LeetCode 1910 Python Solution

MediumStackStringSimulation
Problem
#1910
Pattern
Stack
Reading time
2 min

The 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.

Example

Input
s = "daabcbaabcbc", part = "abc"
Output
"dab"
Explanation
The following operations are done:

Python solution

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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1910. Remove All Occurrences of a Substring is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1910. Remove All Occurrences of a Substring?
LeetCode 1910. Remove All Occurrences of a Substring is rated Medium on LeetCode.
What is the time complexity of LeetCode 1910. Remove All Occurrences of a Substring?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1910. Remove All Occurrences of a Substring?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1910. Remove All Occurrences of a Substring cover?
LeetCode 1910. Remove All Occurrences of a Substring is tagged Stack, String and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview