Nth Digit - Problem

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

The sequence is formed by concatenating all positive integers: 123456789101112131415...

Note: The digit indexing starts from 1 (1-indexed).

Input & Output

Example 1 — Finding 11th Digit
$ Input: n = 11
Output: 0
💡 Note: Sequence: 123456789101112... The 11th digit is the second digit of 10, which is 0
Example 2 — Single Digit
$ Input: n = 3
Output: 3
💡 Note: Sequence: 123456789... The 3rd digit is simply 3
Example 3 — Two-Digit Range
$ Input: n = 15
Output: 2
💡 Note: Sequence: 123456789101112131415... Position 15 is the first digit of 12, which is 1. Wait, let me recalculate: positions 1-9 are digits 1-9, positions 10-11 are '1','0' from 10, positions 12-13 are '1','1' from 11, positions 14-15 are '1','2' from 12. So 15th digit is '2'

Constraints

  • 1 ≤ n ≤ 2³¹ - 1

Visualization

Tap to expand
Nth Digit - Finding the nth digit in infinite sequence INPUT Infinite Integer Sequence: 1 2 3 4 5 6 7 8 9 10 11 12 ... Concatenated String: 1234567891011121314... 1 2 3 ... 9 10 11 Position 11 n = 11 ALGORITHM STEPS 1 Count digits per range 1-9: 9 nums x 1 digit = 9 10-99: 90 nums x 2 digits 2 Find digit range n=11 > 9 (1-digit range) n=11-9=2, in 2-digit range 3 Find the number start=10, digits=2 num = 10 + (2-1)/2 = 10 4 Extract the digit idx = (2-1) % 2 = 1 "10"[1] = '0' digits=1: count=9, start=1 digits=2: count=180, start=10 n=11-9=2 falls in 2-digit num=10, digit_idx=1 --> '0' FINAL RESULT Sequence with positions: 1 1 2 2 ... 9 9 1 10 0 11 1 12 1 13 11th digit Number 10 breakdown: "1" "0" idx 0 idx 1 Output: 0 OK - Verified! Key Insight: Instead of iterating through all digits (O(n)), we use mathematical patterns: 1-digit numbers (1-9): 9 numbers x 1 digit = 9 digits total 2-digit numbers (10-99): 90 numbers x 2 digits = 180 digits total, and so on. Time: O(log n) TutorialsPoint - Nth Digit | Optimal Solution
Asked in
Google 12 Apple 8 Microsoft 6
78.0K Views
Medium Frequency
~25 min Avg. Time
856 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