DDSA Solutions

1910. Remove All Occurrences of a Substring

Time: O(n * k)
Space: O(n)

Problem Overview

Remove All Occurrences of a Substring (Unknown) asks you to solve a structured algorithmic task. This is a common String pattern in coding interviews. Use StringBuilder as a virtual stack; after each append, check if suffix matches part and remove.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Use StringBuilder as a virtual stack; after each append, check if suffix matches part and remove.

Related patterns: String

1910.cs
C#
// Approach: Use StringBuilder as a virtual stack; after each append, check if suffix matches part and remove.
// Time: O(n * k) Space: O(n)

public class Solution
{
    public string RemoveOccurrences(string s, string part)
    {
        int n = s.Length;
        int k = part.Length;

        StringBuilder sb = new StringBuilder(s);
        int j = 0; // sb's index

        for (int i = 0; i < n; ++i)
        {
            sb[j++] = s[i];
            if (j >= k && sb.ToString().Substring(j - k, k) == part)
                j -= k;
        }

        return sb.ToString().Substring(0, j);
    }
}
Was this solution helpful?

Related Problems