LeetCode Entry

3121. Count the Number of Special Characters II

27.05.2026 medium 2026 kotlin rust

Count sorted characters

3121. Count the Number of Special Characters II medium substack youtube

https://dmitrysamoylenko.com/leetcode/

27.05.2026.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1372

Problem TLDR

Count sorted characters

Intuition

Brute-force: checkk all letters separately a..z, last index of c should be in range of 0..first index of C Optimal: bitmasks to track visited uppercase and lowercase and invalid marker

Approach

  • 0.. is essential in kotlin, because lastIndexof can be -1

Complexity

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

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

Code

    fun numberOfSpecialChars(w: String) = ('a'..'z')
    .count { w.lastIndexOf(it) in 0..<w.indexOf(it-32) }
    pub fn number_of_special_chars(w: String) -> i32 {
        (b'a'..=b'z').filter(|&c| w.rfind(c as char)
        .is_some_and(|l| Some(l) < w.find((c - 32) as char))).count() as _
    }

Comments