Remove All Occurrences of a Substring

Given two strings `s` and `part`, repeatedly find the leftmost occurrence of `part` in `s` and remove it, until no occurrence is left. Return `s` after all occurrences of `part` are removed. A substring is a contiguous sequence of characters in a string.

30:00

Remove All Occurrences of a Substring
medium
Free written solution
Topics
Companies

Given two strings s and part, repeatedly find the leftmost occurrence of part in s and remove it, until no occurrence is left. Return s after all occurrences of part are removed. A substring is a contiguous sequence of characters in a string.

Example 1:
Input: {"s":"daabcbaabcbc","part":"abc"}
Output: dab
Constraints:
  • 1≤s.length≤10001 \leq s.\text{length} \leq 1000

  • 1≤part.length≤10001 \leq \text{part.length} \leq 1000

  • ss and part\text{part} consist of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"daabcbaabcbc","part":"abc"}

part

abc

m = 3

s: letters of one removed occurrence share a colour

d
a
a
b
c
b
a
a
b
c
b
c

Scan s once, pushing letters onto a stack. Whenever the top 3 letters spell "abc", cut them off. Removing at the top is always the leftmost occurrence, because everything below it has already been checked.

stack (bottom → top)

size 0

empty

removed 0
Variables
VariableValue
m3
stack
DepthFunction Call
Stack empty
0/26