Search⌘ K
AI Features

Solution: K-th Smallest in Lexicographical Order

Explore how to determine the kth smallest number in lexicographical order by simulating trie traversal. Understand the process of counting numbers under prefixes and navigating the trie to efficiently solve the problem. This lesson helps you apply mathematical reasoning and data structure concepts to optimize your solution for large input values.

Statement

Given two integers, n and k, return the kthk^{th} smallest number in the range [1, n] when the numbers are sorted lexicographically.

Note: Lexicographical sorting means ordering numbers like words in a dictionary (alphabetical order)—digit by digit from left to right. For example, the numerical order of 1, 5, and 10 is [1, 5, 10], but their lexicographical order is [1, 10, 5].

Constraints:

  • 11 \leq k \leq n 109\leq 10^9

Solution

This problem aims to find the kthk^{th} smallest number in the lexicographical (dictionary) order from 11 to n. Instead of generating and sorting all numbers from 11 to n, which would be too slow for large n, let’s take a smarter route by imagining these numbers arranged in a trie. Each node represents a number in a trie, and its children are formed by adding more digits to the end. For example, the root has children 11 to 99, and node 11 has children 1010 ...