DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

2 1

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.

A 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 = "da*abc*baabcbc", remove "abc" starting at index 2, so s = "dabaabcbc".
  • s = "daba*abc*bc", remove "abc" starting at index 4, so s = "dababc".
  • s = "dab*abc*", 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 = "axxx*xy*yyyb", remove "xy" starting at index 4 so s = "axxxyyyb".
  • s = "axx*xy*yyb", remove "xy" starting at index 3 so s = "axxyyb".
  • s = "ax*xy*yb", remove "xy" starting at index 2 so s = "axyb".
  • s = "a*xy*b", 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.

SOLUTION:

class Solution:
    def removeOccurrences(self, s: str, part: str) -> str:
        n = len(part)
        while part in s:
            i = s.index(part)
            s = s[:i] + s[i+n:]
        return s
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay