Nth Digit Problem
Description
LeetCode Problem 400.
Given an integer n, return the n^th digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].
Example 1:
Input: n = 3
Output: 3
Example 2:
Input: n = 11
Output: 0
Explanation: The 11^th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
Constraints:
- 1 <= n <= 2^31 - 1
Solution
Approach: Skip Whole Blocks of Equal-Length Numbers
Writing out the sequence is far too slow for n near 231. Instead, group the numbers by how many digits they have:
| Length | Numbers | Digits in the block |
|---|---|---|
| 1 | 1 – 9 | 9 · 1 = 9 |
| 2 | 10 – 99 | 90 · 2 = 180 |
| 3 | 100 – 999 | 900 · 3 = 2700 |
- Find the block. Start with
length = 1,count = 9,start = 1. Whilenis larger thanlength · count, the digit lies beyond this block: subtract the block's digits fromn, then move to the next block (length + 1,count · 10,start · 10). - Find the number. Inside the block, every number uses
lengthdigits, so the digit belongs tostart + (n - 1) / length(integer division). - Find the digit. It is at position
(n - 1) % lengthof that number, counting from the left.
Using n - 1 makes the position zero-based; using n instead is the usual off-by-one. For n = 11: the first block takes 9 digits, leaving n = 2 in the two-digit block, so the number is 10 + 1 / 2 = 10 and the digit is at position 1 % 2 = 1, which is 0.
length · count reaches about 9 · 109 in the last loop check, so Java and C++ use 64-bit integers for it.
Complexity: O(log n) time, since there are at most 10 blocks, and O(1) space (the number as a string has at most 10 characters).
class Solution:
def findNthDigit(self, n: int) -> int:
length = 1 # digits per number in the current block
count = 9 # how many numbers have this length
start = 1 # the first number with this length
while n > length * count:
n -= length * count
length += 1
count *= 10
start *= 10
number = start + (n - 1) // length
return int(str(number)[(n - 1) % length])
Now write it from memory
Close the write-up and solve it yourself against the tests.