3870. Count Commas in Range
Difficulty: Easy | Published on 2026-09-08
A nice, approachable "Easy" problem — let's still build it up carefully from zero, since even simple-sounding problems can trip you up on the details (like off-by-one digit counting).
1. Problem in Very Simple Language
You're given a number INLINECODE0. Imagine writing out every whole number from 1 to INLINECODE1, one after another, using the normal way we format big numbers with commas — like INLINECODE2 or INLINECODE3.
The rule for where commas go: starting from the rightmost digit and counting leftward, you insert a comma after every group of 3 digits. Numbers with 3 digits or fewer (so, 1 to 999) never get any comma at all.
Your job: count the total number of commas used, if you wrote out every single number from INLINECODE4 to INLINECODE5 this way and added up all the commas across all of them.
What's given: a single integer INLINECODE6. What to find: how many commas appear in total, across the standard-formatted versions of every integer from INLINECODE7 to INLINECODE8. What to return: that total count.
2. Real-Life Analogy
Imagine you're a bank teller printing out receipts for every dollar amount from INLINECODE9 to INLINECODE10, and your printer automatically adds commas to big numbers (like INLINECODE11) the way we normally read money. Some receipts (small amounts, under INLINECODE12) come out with no commas at all. Others (like INLINECODE13) get exactly one comma. Really huge ones would get two or more. You want to know: if you printed every single receipt from INLINECODE14 up through INLINECODE15, how many commas would show up in total, across the whole stack?
3. Important Programming Concepts I Need First
Digit Count of a Number
Concept: How many digits a number has when written normally. INLINECODE16 has 1 digit, INLINECODE17 has 2 digits, INLINECODE18 has 4 digits. Why we need it: The number of commas a number gets depends entirely on how many digits it has — nothing else matters.The comma-counting rule, translated into math
Concept: A comma appears after every group of 3 digits, counting from the right. This means: 1-3 digit numbers → 0 commas. 4-6 digit numbers → 1 comma. 7-9 digit numbers → 2 commas. In general, a number with INLINECODE19 digits gets exactly INLINECODE20 commas, using integer division (which automatically rounds down / drops any remainder). Example: INLINECODE21 → INLINECODE22 comma. INLINECODE23 → INLINECODE24 (integer division drops the INLINECODE25) → still 1 comma (correct: INLINECODE26 has exactly 1 comma). INLINECODE27 → INLINECODE28 commas (correct: INLINECODE29 has 2 commas). Why we need it: This one small formula is the entire mathematical engine behind the whole problem.Integer Division
Concept: When dividing two integers in Java using INLINECODE30, the result is automatically truncated (rounded toward zero) — no decimal part is kept. Example: INLINECODE31 (not INLINECODE32), INLINECODE33. Why we need it: Our comma-count formula, INLINECODE34, relies specifically on this truncating behavior.Loop
Concept: Repeats an action for every item in a range. Why we need it: We need to consider every number from 1 to INLINECODE35 (or, in the optimized version, every possible digit-length group within that range).Grouping by digit length (a new, useful pattern)
Concept: Instead of processing numbers one at a time, notice that all numbers with the same digit count get the exact same number of commas. So instead of asking "how many commas does 1000 get? 1001? 1002?" one at a time, we can ask "how many 4-digit numbers are there in our range, and multiply that count by 1 (the commas each one gets)?" — all at once. Why we need it: This turns our solution into something that only needs to check a tiny handful of digit-length "groups" (since INLINECODE36 can have at most a few digits), rather than looping through every single number.4. Understand the Input
Take Example 1: CODEBLOCK0
We're writing out every number from INLINECODE37 to INLINECODE38. Most of these numbers (1 through 999) have 3 or fewer digits, so they contribute 0 commas each. The numbers INLINECODE39, INLINECODE40, and INLINECODE41 each have 4 digits, so each contributes exactly INLINECODE42 comma. Why does it matter that exactly three numbers (INLINECODE43) fall into the "4-digit" group within our range? Because the total comma count is just "how many numbers are in each digit-length group" multiplied by "how many commas that group's numbers each get," summed across all groups.5. Understand the Output
Output: INLINECODE44
Numbers 1 through 999: 0 digits-group contribution (0 commas each, 999 numbers, INLINECODE45 total commas). Numbers 1000 through 1002: this is a 4-digit group; each number here gets exactly 1 comma; there are 3 such numbers in our range (INLINECODE46); so INLINECODE47 commas. Grand total: INLINECODE48. ✔️ matches!6. Solve the Example Manually
Let's manually work through Example 1 (INLINECODE49) using the "group by digit length" idea.
Step 1: Figure out the digit-length groups that fall (even partially) within INLINECODE50.
1-digit numbers: INLINECODE51 to INLINECODE52 (9 numbers total in this group, all fully within our range since INLINECODE53). 2-digit numbers: INLINECODE54 to INLINECODE55 (90 numbers, fully within range). 3-digit numbers: INLINECODE56 to INLINECODE57 (900 numbers, fully within range). 4-digit numbers: INLINECODE58 to INLINECODE59 normally — but our range stops at INLINECODE60, so only INLINECODE61 to INLINECODE62 actually falls within INLINECODE63 (3 numbers, a partial group).
Step 2: For each group, compute commas-per-number, and how many numbers from that group are actually in INLINECODE64.
| Digit length (d) | Commas per number: (d-1)/3 | Full range of d-digit numbers | Numbers actually in [1, n] | Count in range | Commas contributed |
|---|---|---|---|---|---|
| 1 | (1-1)/3 = 0 | 1 to 9 | 1 to 9 (all fit, since 9 ≤ 1002) | 9 | 9 × 0 = 0 |
| 2 | (2-1)/3 = 0 | 10 to 99 | 10 to 99 (all fit) | 90 | 90 × 0 = 0 |
| 3 | (3-1)/3 = 0 | 100 to 999 | 100 to 999 (all fit) | 900 | 900 × 0 = 0 |
| 4 | (4-1)/3 = 1 | 1000 to 9999 | 1000 to 1002 (capped by n) | 3 | 3 × 1 = 3 |
INLINECODE65. ✔️ matches!
Notice groups 1, 2, and 3 all contribute INLINECODE66 total commas anyway (since INLINECODE67 for INLINECODE68), so really only 4-digit-and-beyond groups can ever contribute anything — but it's still good practice to see the general method applied to every group, since for a bigger INLINECODE69, later groups (5-digit, 6-digit, etc.) would start contributing.
7. Think Like a Programmer
What do I know? Every number's comma count depends only on its digit length, via the formula INLINECODE70. What do I need to find? The sum of comma-counts across every number from 1 to INLINECODE71. What can I try? The most direct approach: loop through every number from 1 to INLINECODE72, figure out its digit length (e.g., by converting to a string and checking its length, or by repeated division), compute its comma count, and add it to a running total. What happens if I try every possibility? With INLINECODE73 capped at INLINECODE74 (per the constraints — INLINECODE75), looping through every single number is only INLINECODE76 iterations — genuinely fast and totally fine for this problem's size. Can I make it faster / cleaner anyway? Yes — since numbers with the same digit length always contribute the same number of commas each, we can process entire digit-length groups at once (as done in Section 6), rather than one number at a time. This is both faster (only a handful of groups to consider, since INLINECODE77 means at most 6 digits) and arguably a cleaner way to think about the problem. What information should I remember? For each digit length INLINECODE78 from 1 upward (until we exceed INLINECODE79), the size of the overlap between "all d-digit numbers" (INLINECODE80 to INLINECODE81) and our actual range (INLINECODE82 to INLINECODE83). What pattern do I notice? This is fundamentally a counting-by-groups problem: instead of processing each individual item, identify a small number of "buckets" (digit-length groups here) where every item in the bucket behaves identically, and process each bucket as a whole.
8. Start With the Brute Force Solution
Brute force idea: Loop through every integer from INLINECODE84 to INLINECODE85. For each one, determine its digit count (e.g., via INLINECODE86), compute its comma count via the formula, and add it to a running sum.
Why it works: It directly computes the comma count for every single number in the range and sums them — a completely literal implementation of the problem statement.
CODEBLOCK1
CODEBLOCK2
Time complexity: INLINECODE87 iterations, and converting each number to a string to get its length takes time roughly proportional to the number of digits (which is at most INLINECODE88) — so overall INLINECODE89 in the strictest sense, though for INLINECODE90 up to INLINECODE91, this is trivially fast regardless.
Space complexity: INLINECODE92 extra (not counting temporary string allocations).
9. Explain the Brute Force Code Line by Line
INLINECODE93 — our running sum, starting at zero. INLINECODE94 — walks through every integer from INLINECODE95 to INLINECODE96, inclusive, exactly as the problem describes. INLINECODE97 — converts the current number INLINECODE98 into its string form (e.g., INLINECODE99 becomes INLINECODE100) and measures how many characters (digits) it has. INLINECODE101 — applies our formula from Section 3: a number with INLINECODE102 digits gets exactly INLINECODE103 commas (using integer division, which naturally truncates/rounds down). INLINECODE104 — adds this number's comma contribution to our running total. INLINECODE105 — after checking every number, return the grand total.
10. Why Might We Want Something Even Cleaner?
For this specific problem, with INLINECODE106 capped at only INLINECODE107, the brute force above is already extremely fast — there's no risk of it being "too slow." But it's worth learning the grouped approach too, both because it's a more elegant/insightful solution, and because it's the kind of technique that would be necessary if INLINECODE108 were allowed to be much larger (say, up into the billions or beyond) — where looping one-by-one would eventually become impractical.
11. Find the Better (Grouped) Approach
"Can we process many numbers at once, instead of one at a time?"
Yes — using the "group by digit length" idea from Section 6:
CODEBLOCK3
⭐ Key Insight
Before the insight
It seems natural to check every number individually to find its comma count.The problem
This is more work than necessary — most of that work is redundant, since large groups of consecutive numbers (all numbers with the same digit length) share the exact same comma count.The insight
A number's comma count depends ONLY on its digit length, via INLINECODE109 — nothing else about the number matters. This means we can skip checking numbers individually altogether, and instead directly compute, for each digit length INLINECODE110, exactly how many numbers of that length fall within our range INLINECODE111 — using simple arithmetic on the boundaries INLINECODE112 and INLINECODE113, capped by INLINECODE114 — then multiply that count by the (fixed) comma count for that digit length.After the insight
The entire problem shrinks from "process up to 100,000 individual numbers" down to "process at most 6 digit-length groups" (since INLINECODE115 means digit lengths only range from 1 to 6), each handled with simple arithmetic.13. Dry Run the Grouped Solution
Let's dry-run Example 2: INLINECODE116.
Digit length 1 (numbers 1-9): Fully within range (INLINECODE117). Count = INLINECODE118. Commas per number = INLINECODE119. Contribution = INLINECODE120.
Digit length 2 (numbers 10-99): Fully within range. Count = INLINECODE121. Commas per number = INLINECODE122. Contribution = INLINECODE123.
Digit length 3 (numbers 100-999, but capped at n=998): The natural range is INLINECODE124 to INLINECODE125, but since INLINECODE126, we cap the upper end at INLINECODE127. Count = INLINECODE128. Commas per number = INLINECODE129 (integer division). Contribution = INLINECODE130.
Digit length 4 and beyond: The natural range would start at INLINECODE131, but our INLINECODE132 is smaller than INLINECODE133 — so there are zero numbers of digit length 4 (or more) within INLINECODE134. We stop here.
Total: INLINECODE135. ✔️ matches!
14. Optimized (Grouped) Code
CODEBLOCK4
CODEBLOCK5
15. Explain the Grouped Code Line by Line
INLINECODE136 — our running sum, same as before. INLINECODE137 — the starting point of the current digit-length group. We begin with 1-digit numbers, which start at INLINECODE138. (We use INLINECODE139 here purely as a safety habit for intermediate arithmetic like INLINECODE140). INLINECODE141 — tracks how many digits the current group's numbers have. INLINECODE142 — we keep processing digit-length groups as long as the start of the next group is still within our range; once a group's start exceeds INLINECODE143, there's nothing left to count. INLINECODE144 — computes the natural upper end of this digit-length group. For example, if INLINECODE145 (3-digit numbers begin here), then INLINECODE146. INLINECODE147 — since our range might not reach all the way to the group's natural end, we cap it using INLINECODE148. INLINECODE149 — standard inclusive range count formula: INLINECODE150. INLINECODE151 — our comma formula from Section 3, applied to this group's shared digit length. INLINECODE152 — adds this entire group's total comma contribution to our running sum all at once. INLINECODE153 — advance to the next digit-length group and increment our digit-length tracker. INLINECODE154 — after all applicable groups have been processed, return the final sum.16. Test With Multiple Examples
Example 1 — Normal Case
INLINECODE155 → dry-ran manually in Section 6 → Output: INLINECODE156 ✔️Example 2 — Different Case
INLINECODE157 → dry-ran in Section 13 → Output: INLINECODE158 ✔️Example 3 — Edge Case (very small n)
INLINECODE159. INLINECODE160, which is INLINECODE161: INLINECODE162, INLINECODE163, INLINECODE164, INLINECODE165, contribution = INLINECODE166. INLINECODE167. Next INLINECODE168 becomes INLINECODE169, loop terminates. Output: INLINECODE170 ✔️17. Edge Cases
INLINECODE171 (smallest possible input) → only the single number INLINECODE172 is considered, which trivially has 0 commas → output INLINECODE173. INLINECODE174 exactly at a "boundary" like INLINECODE175 or INLINECODE176 → correctly handled by the INLINECODE177 capping — e.g., INLINECODE178 never enters the 4-digit group loop iteration, while INLINECODE179 does enter it with INLINECODE180 correctly capped at INLINECODE181. INLINECODE182 such that no group ever reaches 4+ digits (INLINECODE183) → every group's INLINECODE184 evaluates to INLINECODE185, so the total is always INLINECODE186. Maximum INLINECODE187 (up to INLINECODE188, i.e., 6 digits) → our loop runs at most 6 times, executing in microseconds. INLINECODE189 right at a power of 10 transition — naturally handled by the group-boundary math.
18. Time Complexity
What is time complexity? An estimate of how the amount of work grows as the input grows, using a general trend.
CODEBLOCK6
Why: In the grouped approach, we never look at individual numbers — we only ever process one group per possible digit length (at most 6 for INLINECODE190, and at most 10 for any 32-bit integer).
19. Space Complexity
Both approaches use only a small, fixed number of extra variables (INLINECODE191, INLINECODE192, INLINECODE193). Extra space: INLINECODE194.
20. Common Mistakes Beginners Make
❌ "The comma formula should be INLINECODE195, without the INLINECODE196." ✅ It must be INLINECODE197 — for INLINECODE198, INLINECODE199 would wrongly suggest 3-digit numbers get a comma, whereas INLINECODE200 correctly gives zero. ❌ "The group boundaries should be INLINECODE201 to INLINECODE202." ✅ Careful with off-by-one: 1-digit numbers are INLINECODE203 to INLINECODE204, 2-digit are INLINECODE205 to INLINECODE206, 3-digit are INLINECODE207 to INLINECODE208. Pattern: starts at INLINECODE209, ends at INLINECODE210. ❌ "I don't need to cap the group's end using INLINECODE211." ✅ When INLINECODE212 falls within a digit-length group, capping with INLINECODE213 is essential to avoid overcounting numbers greater than INLINECODE214. ❌ "This requires string formatting." ✅ The problem reduces entirely to digit-counting mathematics without any string allocations.
21. How to Recognize This Pattern in Other Problems
Watch for these signal phrases:
CODEBLOCK7
Whenever a per-number property is shared by large groups of consecutive numbers, think: process by group, not by individual number — compute INLINECODE215 across $O(\log{10} N)$ groups.
22. Interview Thinking
CODEBLOCK8
23. Mini Challenge
Try these before checking the answers:
1. Why does the formula INLINECODE216 give INLINECODE217 for any INLINECODE218 of 1, 2, or 3, but INLINECODE219 for digitCount of 4, 5, or 6? 2. If INLINECODE220, which digit-length groups would be processed, and would any of them need INLINECODE221 capping applied? 3. Why does the grouped approach only ever need to loop a handful of times, no matter how big INLINECODE222 gets (within reason)?
Answer to Mini Challenge
1. Integer division INLINECODE223 only increments when INLINECODE224 crosses multiples of 3. For INLINECODE225: INLINECODE226 is INLINECODE227 (all yield INLINECODE228). For INLINECODE229: INLINECODE230 is INLINECODE231 (all yield INLINECODE232). This mirrors the standard 3-digit comma rule. 2. For INLINECODE233 (5 digits): groups 1 (1-9), 2 (10-99), 3 (100-999), 4 (1000-9999) are fully included. Group 5 (10000-99999) is capped at INLINECODE234. 3. The number of groups equals the number of digits in INLINECODE235, which is at most 10 for standard 32-bit integers.
24. Final Revision
🧠 Problem in One Sentence
Count the total number of commas across the standard-formatted versions of every integer from 1 to INLINECODE236.🔑 Main Idea
A number's comma count depends only on its digit length via INLINECODE237. Process entire digit-length groups at once, multiplying each group's size by its shared comma count.⚙️ Algorithm
1. For each digit length INLINECODE238 starting at 1, find that group's natural range (INLINECODE239 to INLINECODE240). 2. Cap the group's upper end at INLINECODE241 if needed (INLINECODE242). 3. If INLINECODE243, stop. 4. Otherwise, add INLINECODE244 to the total. 5. Advance to the next power of 10 and repeat.⏱️ Complexity
Time: INLINECODE245 (grouped)- Space:
🎯 Pattern to Remember
When properties are uniform across digit ranges, group by powers of 10 to turn $O(N)$ simulations into $O(\log N)$ range calculations.25. Beginner Quiz
1. (Understanding) Why do numbers with 1, 2, or 3 digits never contain any commas? 2. (Basic concept) What is
INLINECODE247 using integer division, and what does that tell you about how many commas a 7-digit number has? 3. (Logic) Why is INLINECODE248 necessary when computing a group's actual upper bound? 4. (Dry run) For INLINECODE249, determine which digit-length groups get processed, their capped ranges, and the final total comma count. 5. (Complexity/pattern) Given that INLINECODE250 is capped at only INLINECODE251 in this specific problem, why is the simple INLINECODE252 brute-force loop perfectly acceptable here, and under what circumstances would you need the grouped INLINECODE253_ approach instead?