#440

K-th Smallest in Lexicographical Order

Hard
TriePrefix TreeCounting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n log n)
O(log n)
Space
O(n)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Instead of generating all numbers, we can use a prefix-based counting approach. By treating the numbers as a tree, we can count how many numbers exist under a given prefix and navigate through this tree to find the k-th smallest number efficiently.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize current prefix as 1.
  2. 2Step 2: Count how many numbers exist with the current prefix in the range [1, n].
  3. 3Step 3: If the count is less than k, move to the next prefix (current prefix + 1).
  4. 4Step 4: If the count is greater than or equal to k, move down the tree (current prefix * 10).
  5. 5Step 5: Repeat until k-th number is found.
solution.py18 lines
1def findKthNumber(n, k):
2    current = 1
3    k -= 1
4    while k > 0:
5        count = 0
6        first = current
7        last = current + 1
8        while first <= n:
9            count += min(n + 1, last) - first
10            first *= 10
11            last *= 10
12        if count <= k:
13            current += 1
14            k -= count
15        else:
16            current *= 10
17            k -= 1
18    return current

Complexity note: The time complexity is O(log n) due to the logarithmic depth of the tree we traverse, and the space complexity is O(1) since we only use a few variables.

  • 1Understanding the structure of numbers can help optimize the search for the k-th smallest.
  • 2Using a prefix tree-like approach allows us to count efficiently without generating all numbers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.