
Count Commas in Range - LeetCode-3870 Solution
Today we're looking at Count Commas in Range . It's a pretty interesting problem that can easily trick you into writing a slow solution, especially once the constraints get big. Let's break it down. The Problem Problem Link We're given an integer n . We need to figure out the total number of commas used when writing all integers from 1 to n in standard format. 999 → 0 commas 1,000 → 1 comma 1,000,000 → 2 commas We just return the total sum of all those commas. Example 1: Input: n = 1000 Output: 1 Example 2: Input: n = 1000000 Output: 2998001 Brute Force The most obvious way is to just loop through every number from 1 to n , count its commas, and add to a running total. def countCommas ( n : int ) -> int : total = 0 for i in range ( 1 , n + 1 ): digits = len ( str ( i )) total += ( digits - 1 ) // 3 return total Does that work? Technically, yes. But look at the constraints. If n goes up to 10^15 , an O(n) solution is way too slow. Time Limit Exceeded. We need a math approach. Intuition
Continue reading on Dev.to Python
Opens in a new tab



