The problem is to find the Nth digit of the infinite sequence of positive integers “123456789101112131415161718192021…”. The sequence is formed by concatenating the positive integers consecutively.
n
?
To determine the Nth digit in this sequence, we can break down the sequence into segments based on the number of digits in the numbers:
Steps:
n
accordingly.public int findNthDigit(int n) {
if (n < 10) return n;
int digitLength = 1;
long count = 9;
int start = 1;
// Determine the digit length and starting number of the range containing the nth digit
while (n > digitLength * count) {
n -= digitLength * count;
digitLength++;
count *= 10;
start *= 10;
}
// Determine the actual number within the range
start += (n - 1) / digitLength;
// Determine the index of the digit in the final number
String number = Integer.toString(start);
int digitIndex = (n - 1) % digitLength;
// Return the digit
return number.charAt(digitIndex) - '0';
}
The time complexity of this solution is O(log n) due to the while loop, which effectively reduces the value of n
by a significant factor each iteration. The operations inside the loop (digit calculations and string operations) are constant time and less impactful.
n
down while skipping entire ranges of numbers until we identify the range that contains the Nth digit.This strategy ensures that we efficiently find the Nth digit without constructing the huge sequence.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?