LeetCode Entry

3174. Clear Digits

10.02.2025 easy 2025 kotlin rust

Remove [char][digit] pairs from string

3174. Clear Digits easy blog post substack youtube 1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/891

Problem TLDR

Remove [char][digit] pairs from string #easy

Intuition

Go forwards or backwards. Use builders, pointers or replace in-place.

Approach

  • how about recursion + regex?

Complexity

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

  • Space complexity: \(O(n)\), O(1) for in-place

Code


    fun clearDigits(s: String) = buildString {
        for (c in s) if (c.isLetter()) append(c) else setLength(lastIndex)
    }


    pub fn clear_digits(mut s: String) -> String {
        let mut b = 0;
        for i in (0..s.len()).rev() {
            if (b'0'..=b'9').contains(&s.as_bytes()[i]) { b += 1; s.remove(i); }
            else { if b > 0 { s.remove(i); }; b = 0.max(b - 1) }
        }; s
    }


    string clearDigits(string s) {
        string x = regex_replace(s, regex("\\D\\d"), "");
        return x == s ? x : clearDigits(x);
    }