Problem Description
Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]. For example, when n = 11, the output is 0 because the 11th digit corresponds to the digit 0 in the number 10.
Key Insights
- The infinite sequence can be split into groups based on the number of digits (1-digit, 2-digit, etc.).
- Calculate the total number of digits in each group to determine where the nth digit falls.
- Once the correct group is identified, compute the exact number and then the specific digit within that number.
Space and Time Complexity
Time Complexity: O(log n)
Space Complexity: O(1)
Solution
We first determine the group (digit length) where the nth digit lies by subtracting the count of digits in each group (for 1-digit numbers, 2-digit numbers, etc.) from n until n is small enough to be within a particular group. Once the group is identified, we compute the starting number of that group (10^(digitLength - 1)). We then calculate the exact number that contains the nth digit using the offset (n-1) / digitLength, and finally find the required digit using modulo (n-1) % digitLength. This approach is efficient as it iterates through groups logarithmically with respect to n and uses only constant space.