LeetCode Entry

1910. Remove All Occurrences of a Substring

11.02.2025 medium 2025 kotlin rust

Remove substring recursively

1910. Remove All Occurrences of a Substring medium blog post substack youtube 1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/892

Problem TLDR

Remove substring recursively #medium

Intuition

The problem size is 1000, we can use n^2 brute-force.

Approach

  • the order matters

Complexity

  • Time complexity: \(O(n^2)\)

  • Space complexity: \(O(n)\)

Code


    fun removeOccurrences(s: String, part: String) =
        s.fold("") { r, c -> (r + c).removeSuffix(part) }


    pub fn remove_occurrences(mut s: String, part: String) -> String {
        while let Some(i) = s.find(&part) {
            s.replace_range(i..i + part.len(), "")
        }; s
    }


    string removeOccurrences(string s, string part) {
        while (size(s) > s.find(part)) s.erase(s.find(part), size(part));
        return s;
    }