K-th Smallest in Lexicographical Order LeetCode solution in Python
1class Solution:2def findKthNumber(self, n: int, k: int) -> int:34def prefix(op, n):5if op == n:6return 17if int(op) > int(n):8return 09for i in range(len(op)):10if int(op[i]) > int(n[i]):11rem = len(n) - 1 - len(op)12if not rem:13return 114return 1 + int(10 * ((1 - 10**rem) / -9))15elif int(op[i]) < int(n[i]):16rem = len(n) - len(op)17if not rem:18return 119return 1 + int(10 * ((1 - 10**rem) / -9))2021res = 122for i in range(10):23res += prefix(op + str(i), n)24return res2526ans = 127while k > 1:28pref = prefix(str(ans), str(n))29if pref >= k:30ans *= 1031k -= 132else:33ans += 134k -= pref3536return ans