Nth Digit solution explained
Nth Digit asks for the digit at position n when the positive integers are written one after another as 123456789101112 and so on. Skip whole blocks of numbers that share a digit count (9 one-digit numbers, 90 two-digit, 900 three-digit), then compute which number and which digit inside it you landed on. That takes O(log n) time and O(1) space.
By Evin JohnPublished 7 min read
What is being asked
Write 1, 2, 3 and every following positive integer back to back with no separators, forming one endless line of digits. Given a position n, counting from 1, return the digit found there. n can be large, often up to about two billion, so building the line is out.
| n | Digit | Where it comes from |
|---|---|---|
| 7 | 7 | Still inside the single-digit numbers |
| 12 | 1 | First digit of 11 |
| 15 | 2 | Second digit of 12 |
| 190 | 1 | First digit of 100, right after the two-digit block ends at 189 |
| 1000 | 3 | First digit of 370 |
Brute force: build the string
Append numbers to a buffer until it holds at least n characters, then read position n - 1. It is easy to trust and makes a perfect test oracle, but it costs O(n) time and memory. At two billion characters that is gigabytes of text.
def nth_digit_slow(n):
parts, length, k = [], 0, 0
while length < n:
k += 1
s = str(k)
parts.append(s)
length += len(s)
return int("".join(parts)[n - 1])Counting digits block by block
Group the integers by how many digits they have. There are 9 numbers with one digit, 90 with two, 900 with three, and in general 9 times 10 to the power d - 1 numbers with d digits. A block of d-digit numbers therefore fills d times that many positions: 9, then 180, then 2,700, then 36,000.
- Start at the one-digit blockTrack
width(digits per number, starting at 1),block(how many numbers have that width, starting at 9) andfirst(the first number of that width, starting at 1). - Skip blocks that end before nWhile n is larger than
width * block, subtract that amount from n and move to the next block: width plus one, block and first times ten. - Pick the numberNow n is a 1-based position inside the current block. The number is
first + (n - 1) // width. - Pick the digitThe digit's index inside that number is
(n - 1) % width, counted from the left.
def nth_digit(n):
width, block, first = 1, 9, 1
while n > width * block:
n -= width * block
width += 1
block *= 10
first *= 10
number = first + (n - 1) // width
return int(str(number)[(n - 1) % width])function nthDigit(n) {
let width = 1;
let block = 9;
let first = 1;
while (n > width * block) {
n -= width * block;
width += 1;
block *= 10;
first *= 10;
}
const number = first + Math.floor((n - 1) / width);
return Number(String(number)[(n - 1) % width]);
}The loop runs once per digit width, so about ten times for any n that fits in 32 bits. The final step converts one number to a string, which is also tiny. If an interviewer bans string conversion, divide the number by 10 to the power (width - 1 - index) and take the result modulo 10.
Worked example: n = 1000
The one-digit block uses 9 positions, so n becomes 991. The two-digit block uses 180, so n becomes 811. The three-digit block would use 2,700, which is more than 811, so we stop with width 3 and first 100. The number is 100 + 810 // 3 = 370, and the digit index is 810 % 3 = 0, the first digit of 370. The answer is 3.
Alternative: binary search on the number
When this problem shows up in a binary search practice list, it is usually there for a different framing. Define D(x) as the number of digits used to write 1 through x. D is increasing and cheap to compute block by block. Binary search for the smallest x with D(x) at least n: that x is the number containing position n, and n - D(x - 1) tells you which of its digits.
def digits_through(x):
total, width, first = 0, 1, 1
while first <= x:
last = min(x, first * 10 - 1)
total += (last - first + 1) * width
width += 1
first *= 10
return total
def nth_digit_bisect(n):
lo, hi = 1, n
while lo < hi:
mid = (lo + hi) // 2
if digits_through(mid) >= n:
hi = mid
else:
lo = mid + 1
s = str(lo)
return int(s[n - digits_through(lo - 1) - 1])This costs O(log² n) instead of O(log n), so the block-skipping loop is still the cleaner primary answer. The binary search version is worth knowing because the same shape, a monotone count plus a search for the first value that reaches a target, solves several other problems in this set.
Complexity summary
| Approach | Time | Space |
|---|---|---|
| Build the digit string | O(n) | O(n) |
| Skip digit-width blocks | O(log n) | O(1) |
| Binary search on the number | O(log² n) | O(1) |
Boundary positions
- n = 1 returns 1, and n = 9 returns 9: still in the first block.
- n = 10 and n = 11 are the two digits of 10, so they return 1 and 0.
- n = 189 is the last digit of 99, and n = 190 is the first digit of 100. Off-by-one bugs show up exactly at these block edges.
- Very large n, near two billion. The loop is still short, but
width * blockreaches about 8.1 billion (width 9 times 900 million numbers), well past a 32-bit int. - Inputs of 0 or below are invalid in the usual statement; ask, then guard if needed.
Mistakes interviewers see
- Mixing 0-based and 1-based positions. Convert once, as the
n - 1in both formulas does, and stick with it. - Using `n // width` instead of `(n - 1) // width`. At the last digit of each number this jumps to the next number.
- Integer overflow in Java or C++.
width * blockandfirstcan exceed a 32-bit int for large n. Use a 64-bit type for those variables. - Comparing with `>=` in the skip loop. If n equals the block size exactly, it is the last digit of the block, not the first of the next one.
- Building the string "just to be safe". It passes small tests and runs out of memory or time on large ones.
A sample explanation
Fictional example
- Candidate
- I will not build the string. Numbers come in blocks by digit count: 9 numbers of width one, 90 of width two, 900 of width three. Each block uses width times count positions.
- Candidate
- I subtract whole blocks while n is past them. Then n is a 1-based offset inside one block, so the number is the block's first value plus (n - 1) divided by the width, and the remainder picks the digit.
- Candidate
- That is one loop step per digit width, so logarithmic time and constant space. In Java I would make those counters long.
Related walkthroughs
Kth Smallest Number in Multiplication Table and Median of a Row-Wise Sorted Matrix both rely on the monotone-count search shown in the alternative above. Single Element in a Sorted Array is a quick binary search over indexes for warming up. The algorithm interview questions guide lists other math-flavored topics.
Natively for mock rounds
While you drill problems like this one, Natively can scan a screenshot of the prompt and suggest how to approach it, so you can compare notes after your own attempt. It also transcribes practice interviews on your computer, which makes it easy to spot whether you explained the block edges or rushed past them. The AI interview assistant page describes how it works.
Questions people ask
How do you solve the Nth Digit problem?
Subtract whole blocks of numbers that share a digit count (9 one-digit numbers, then 90 two-digit, and so on) until n falls inside a block. Then the number is the block's first value plus (n - 1) divided by the width, and the remainder picks the digit.
What is the time complexity of Nth Digit?
O(log n) time and O(1) space, because the loop runs once per digit width. Building the digit string instead takes O(n) time and memory.
Can Nth Digit be solved with binary search?
Yes. Count the digits used to write 1 through x, which grows with x, and binary search for the smallest x whose count reaches n. That is O(log² n), slightly slower than skipping blocks.
What are the common off-by-one errors?
Using n instead of n - 1 when dividing by the width, and skipping a block when n exactly equals its size. Test positions 9, 10, 189 and 190, which sit on block edges.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
