Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: The infinite string 123456789101112… is indexed from 1. Find the n-th digit by skipping whole blocks of 1-digit, 2-digit, … numbers.

Problem: The infinite string 123456789101112… is indexed from 1. Find the n-th digit by skipping whole blocks of 1-digit, 2-digit, … numbers.
def nth(n):
    length, count, start = 1, 9, 1
    while n > length * count:
        n -= length * count; length += 1; count *= 10; start *= 10
    num = start + (n - 1) // length
    return int(str(num)[(n - 1) % length])
print(nth(11), nth(190), nth(1000))
What is printed?
  1. A. 1 0 9
  2. B. 0 9 3
  3. C. 1 1 3
  4. D. 0 1 3

Correct answer: D. 0 1 3

Digits 1–9 are one-digit numbers; 10–99 contribute 180 digits (positions 10–189). n = 11 is the second digit of 10 → 0. n = 190 is the first digit of 100 → 1. n = 1000: subtract 9 and 180 → 811th digit among 3-digit numbers: number 100 + 270 = 370, digit index 0 → 3.

More Coding Interview Problems questions

Exams that ask this topic