Skip to content
Problem 400 · LeetCode 400(opens in a new tab)

Nth Digit

MediumBinary search

Write the positive integers one after another with nothing between them: 1234567891011121314... and so on forever.

Given n, return the digit at position n of that string, counting from 1.

Example 1

Input:  n = 15
Output: 2
Why:    1 to 9 give 9 digits, then 10 11 12 give 6 more; the 15th is the 2 of 12
2 more examples and the constraints

Example 2

Input:  n = 7
Output: 7
Why:    the first nine digits are just 1 to 9

Example 3

Input:  n = 190
Output: 1
Why:    1 to 99 use 189 digits, so the 190th is the first digit of 100

Constraints

  • 1 ≤ n ≤ 2,147,483,647 (2^31 − 1)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Skip whole groups by lengthO(log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 2^31 − 1Verdict
Binary search on the numberO(log² n)
Passes; about 300 steps
Skip whole groups by lengthO(log n)
Best; about 10 steps

n = the position asked for. Writing the numbers out one by one would be O(n).

Edge cases to test

  • Inside the first group. For n ≤ 9 the answer is n itself.
  • A zero digit. n = 11 lands on the 0 of 10.
  • Group boundary. n = 189 is the last 9 of 99; n = 190 starts 100.
  • The largest n. n = 2,147,483,647 lands among the 9-digit numbers; length · count passes 32 bits on the way, so use 64-bit math.

Common mistakes

  • Using n instead of n − 1 for the number or the digit index, which is off by one.
  • Computing length · count in 32-bit integers, which overflows for large n.
  • Writing the sequence out digit by digit, which is far too slow near 2^31.

How to talk through it

  1. 1Clarify. Does counting start at 1? Is the sequence 1, 2, 3, ... with no separators?
  2. 2Name the slow way. Writing the numbers out works but takes about n steps.
  3. 3Group by length. There are 9 · 10^(k−1) numbers with k digits, using k times that many digits.
  4. 4Divide to land. Inside the group, (n − 1) / length picks the number and (n − 1) mod length picks the digit.
  5. 5Test out loud. Run n = 7, 11, 189, 190 and 2^31 − 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?