LeetCode Entry

3871. Count Commas in Range II

09.09.2026 medium 2026 kotlin rust

Count commas in numbers range

3871. Count Commas in Range II medium substack youtube

https://dmitrysamoylenko.com/leetcode/

09.09.2026.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1477

Problem TLDR

Count commas in numbers range

Intuition

Number can be big 10^15. All numbers except first 999 have the first comma, all except frist 999999 has second comma and so on.

Approach

  • can write a loop

Complexity

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

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

Code

    fun countCommas(n: Long) =
    (0..4).sumOf{max(0L,n-"999".repeat(it + 1).toLong())}
    pub fn count_commas(n: i64) -> i64 {
        (1..6).map(|i| (n + 1 - 10i64.pow(i * 3)).max(0)).sum()
    }

Comments