Nth Digit - Problem

Imagine an infinite sequence of positive integers written without any separators: 123456789101112131415.... Your task is to find the nth digit in this sequence.

Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ...].

Key insights:

  • Single-digit numbers (1-9) contribute 9 digits
  • Two-digit numbers (10-99) contribute 90 ร— 2 = 180 digits
  • Three-digit numbers (100-999) contribute 900 ร— 3 = 2700 digits
  • And so on...

The challenge is to efficiently determine which number contains the nth digit and which position within that number.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 3
โ€บ Output: 3
๐Ÿ’ก Note: The sequence is 123456789101112... The 3rd digit is 3.
example_2.py โ€” Two-Digit Range
$ Input: n = 11
โ€บ Output: 0
๐Ÿ’ก Note: The sequence is 123456789101112... Positions 1-9 are single digits (123456789), position 10 is '1' from '10', position 11 is '0' from '10'.
example_3.py โ€” Edge Case
$ Input: n = 15
โ€บ Output: 2
๐Ÿ’ก Note: The sequence is 123456789101112131415... Position 15 falls on the second digit of number 12, which is '2'.

Constraints

  • 1 โ‰ค n โ‰ค 231 - 1
  • n is guaranteed to be valid
  • The sequence starts from 1 (not 0)

Visualization

Tap to expand
Nth Digit Pattern AnalysisSequence: 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 ...1-Digit NumbersRange: 1 - 9Count: 9 numbersTotal: 9 digits2-Digit NumbersRange: 10 - 99Count: 90 numbersTotal: 180 digits3-Digit NumbersRange: 100 - 999Count: 900 numbersTotal: 2700 digitsFinding Digit at Position 15:1Check 1-digit range: 15 > 9, so not here2Check 2-digit range: 15 โ‰ค 9 + 180, so it's here!3Remaining position: 15 - 9 = 64Target number: 10 + (6-1)รท2 = 10 + 2 = 125Position in number: (6-1) % 2 = 16Answer: 12[1] = '2'Visual Sequence Breakdown1 2 3 4 5 6 7 8 9 | 1 0 | 1 1 | 1 2 | 1 3 | 1 4 | 1 5 ...1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 (positions)2
Understanding the Visualization
1
Pattern Recognition
1-digit numbers (1-9) contribute 9 digits total
2
Range Expansion
2-digit numbers (10-99) contribute 90ร—2=180 digits
3
Mathematical Jump
Skip entire ranges to find target number quickly
4
Precise Extraction
Calculate exact position within the target number
Key Takeaway
๐ŸŽฏ Key Insight: Instead of counting digit by digit, use mathematical patterns to calculate which number contains the nth digit and extract it directly in O(log n) time.
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 25
45.2K Views
Medium Frequency
~25 min Avg. Time
1.7K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen