diff --git a/hard/k_th_smallest_in_lexicographical_order.py b/hard/k_th_smallest_in_lexicographical_order.py new file mode 100644 index 0000000..1f73dcc --- /dev/null +++ b/hard/k_th_smallest_in_lexicographical_order.py @@ -0,0 +1,24 @@ +# https://leetcode.com/problems/k-th-smallest-in-lexicographical-order + +class Solution: + def findKthNumber(self, n: int, k: int) -> int: + def max_step(curr: int) -> int: + step = 0 + first, last = curr, curr + while first <= n: + step += min(n, last) - first + 1 + first *= 10 + last = last * 10 + 9 + return step + curr = 1 + k -= 1 + while k > 0: + step = max_step(curr) + if step <= k: + k -= step + curr += 1 + else: + k -= 1 + curr *= 10 + return curr +