K-th Digit in Infinite String Problem
Description
LeetCode Problem 4022.
You are given an integer k.
An infinite string is formed by concatenating the decimal representations of the positive integers, without separators.
For every nonnegative integer b, block b contains the positive integers from 10 * b through 10 * b + 9. The integers in each block are appended as follows:
- If
bis even, append the integers in increasing order. - If
bis odd, append the integers in decreasing order.
Therefore, the string starts with the integers 1 through 9, followed by 19 through 10, then 20 through 29, then 39 through 30, and so on.
Return the k^th digit (1-indexed) of this string.
Example 1:
Input: k = 4
Output: 4
Explanation:
The string begins as "123456789..". The 4^th digit is '4'.
Example 2:
Input: k = 15
Output: 7
Explanation:
The string begins as "123456789191817..". The 15^th digit is '7'.
Example 3:
Input: k = 11
Output: 9
Explanation:
The string begins as "12345678919..". The 11^th digit is '9'.
Constraints:
1 <= k <= 10^15
Solution
Approach: Mathematics
Block b holds the integers 10b to 10b + 9: ascending when b is even, descending when b is odd. Digits 1 to 9 come first (9 digits).
Group the rest by the number of digits d = 2, 3, .... The d-digit numbers fill blocks 10^(d-2) up to 10^(d-1) - 1, that is 9 * 10^(d-2) blocks, and each block contributes 10 * d digits. Subtract whole groups from k until the group holding the k-th digit is found.
Inside that group the block is b = start + (k - 1) / (10d) and the offset in the block is pos = (k - 1) % (10d). The number is the pos / d-th one of the block, counted in the block's own order (ascending for even b, descending for odd b), and the digit is index pos % d of it.
Complexity: time O(log k), space O(1).
class Solution:
def kthDigit(self, k: int) -> int:
if k <= 9:
return k
k -= 9
d = 2
start = 1
while True:
cnt = 9 * 10 ** (d - 2)
size = 10 * d
if k <= cnt * size:
break
k -= cnt * size
d += 1
start *= 10
b = start + (k - 1) // size
pos = (k - 1) % size
i = pos // d
num = 10 * b + i if b % 2 == 0 else 10 * b + 9 - i
return int(str(num)[pos % d])