From b96b438b8a43a851fdffca36252a484360e7f7f9 Mon Sep 17 00:00:00 2001 From: bumpsoo Date: Mon, 9 Jun 2025 13:58:01 +0000 Subject: [PATCH] https://leetcode.com/problems/k-th-smallest-in-lexicographical-order --- .../k_th_smallest_in_lexicographical_order.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 hard/k_th_smallest_in_lexicographical_order.py 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 +