Count How Many Times Digit One Appears From 1 to N
Last updated: November 29, 2026
Quick Overview
Return the total number of times the digit 1 is written when listing every integer from 1 to n, for n up to 10^18, as when printing sequential post IDs.
Meta
November 29, 20260
0
0 solved
Return the total number of times the digit 1 is written when listing every integer from 1 to n, for n up to 10^18, as when printing sequential post IDs.
A Meta onsite math question that rewards per-position counting over brute force. The interviewer wants a correct case analysis on the current digit being 0, 1, or greater, and clean handling of the high and low parts.
What the Interviewer Expects
- Reject brute force for large n
- Count contributions position by position
- Split n into high, current, and low parts at each position
- Handle the three cases for the current digit
- Verify against brute force on small n
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Generalize to any digit d, including the special case d = 0.
- Count numbers in [a, b] containing at least one 1.
- Write the digit DP version and compare.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: integer n with 0 <= n <= 10^18. Output: total count of digit '1' across the decimal representations of 1..n. Example: n = 13 gives 6 (1, 10, 11 twice, 12, 13)....
High-Level Design
For each position with place value p (1, 10, 100, ...), split n into high = n // (10p), cur = (n // p) % 10, and low = n % p. Count how many numbers in 1..n have a 1 at that position:
- Full cy...