Python 0440.py
class Solution:
def findKthNumber(self, n: int, k: int) -> int:
# if n == 99 then there are 10 numbers between 1 and 2 (and 10 between 2 and 3, 3 and 4, ...)
# if n == 999 then there are 100 numbers between 1 and 2 (and 100 between 2 and 3, 3 and 4, ...)
# ...
result = 1
k -= 1
while k > 0:
start = result
end = result + 1
# count numbers between start and end (in lexicographical order)
covered = 0
while start <= n:
covered += min(end, n + 1) - start
start *= 10
end *= 10
if covered > k:
result *= 10
k -= 1
else:
result += 1
k -= covered
return result
Difficulty
and has an acceptance rate of about 46% (300k+ submissions).
Typical patterns to solve this problem:
- Trie
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the k-th smallest integer in the range [1, n] when the numbers are ordered lexicographically. It treats the set of numbers as a virtual prefix tree (trie) where each node represents a numeric prefix. By navigating this tree, the algorithm efficiently skips whole sub-ranges that are lexicographically before the desired position, thereby avoiding a full enumeration of all numbers.
Core Logic
The algorithm starts with the smallest possible result, 1, and decrements k because the first number in lexicographical order is already accounted for. A loop runs while k remains positive, repeatedly deciding whether to descend deeper into the current prefix or to move to the next sibling prefix.
result = 1
k -= 1
while k > 0:
...
Inside the loop the variables start and end define the current prefix interval [start, end). The inner loop counts how many numbers in the whole range [1, n] share this prefix, including all deeper levels of the trie.
start = result
end = result + 1
covered = 0
while start <= n:
covered += min(end, n + 1) - start
start *= 10
end *= 10
After the count is obtained, the algorithm compares covered with the remaining k. If the current prefix subtree contains more numbers than needed, the algorithm descends one level by appending a zero to the prefix (result *= 10) and consumes a single step (k -= 1). Otherwise it skips the entire subtree, moves to the next sibling (result += 1), and reduces k by the size of the skipped subtree (k -= covered).
if covered > k:
result *= 10
k -= 1
else:
result += 1
k -= covered
When k reaches zero, result holds the required k-th lexicographical number and is returned.
Lexicographical Counting
The counting block works by repeatedly expanding the interval [start, end) by a factor of ten, which corresponds to moving one level deeper in the trie. At each depth, the number of valid integers contributed by that level is the overlap between the interval and the bound [1, n]. The expression min(end, n + 1) - start yields exactly that overlap, handling the situation where the interval exceeds n.
Because the loop multiplies start and end by ten each iteration, it naturally stops when start exceeds n. This ensures that only prefixes that could possibly generate numbers within the bound are considered.
Traversal Decisions
The decision branch distinguishes two scenarios:
When the subtree under the current prefix is larger than the remaining offset (covered > k).
In this case the algorithm knows the target lies somewhere inside the subtree, so it moves down one level (result *= 10). Consuming one step (k -= 1) reflects the fact that the current prefix itself counts as the first element of its subtree.
When the subtree is not large enough (covered <= k).
Here the target is beyond the entire subtree, so the algorithm skips it entirely, advances to the next sibling (result += 1), and subtracts the whole subtree size from k. This bulk skip avoids iterating over each individual number in the skipped range.
Edge Cases Handled
The code correctly processes the situation where n has trailing nines, such as 99 or 999. In those cases the count of numbers between consecutive prefixes grows by a factor of ten at each additional digit length, and the counting loop automatically captures that growth because the multiplication by ten expands the interval appropriately.
When k equals 1, the initial decrement (k -= 1) reduces k to zero, causing the outer loop to be bypassed entirely and the function to return 1, which is the correct first lexicographical number.
If k points to the last number in the lexicographical order, the algorithm will repeatedly skip entire subtrees until it reaches the final prefix. The subtraction k -= covered ensures that the remaining offset is accurately updated even when large blocks are skipped.
When n is a single-digit number, the inner counting loop executes only once because start * 10 immediately exceeds n. The algorithm therefore behaves like a simple linear scan over the digits, which is appropriate for such small ranges.
Performance Considerations
The primary optimization lies in the ability to skip whole prefix subtrees in constant time per depth level. By computing covered with arithmetic rather than enumerating each number, the algorithm reduces the work from O(n) to O(log n) traversals of the prefix tree. The multiplication by ten and the use of min keep the arithmetic operations simple and fast.
Because the outer loop iterates at most the number of digits needed to reach the k-th element, and each inner loop iterates proportionally to the depth of the current prefix, the total number of iterations grows logarithmically with n. This makes the solution scalable even for very large values of n and k.
The use of integer arithmetic only (no string conversions) avoids the overhead associated with constructing or comparing string representations of numbers, further contributing to runtime efficiency.
ELI5 - Simplified Explanation
Imagine you have a big pile of number cards from one to as many as you want. Usually, we count numbers like one, two, three, four, five, six, seven, eight, nine, and then ten. But this code likes to sort them like words in a dictionary. In this special way, the number ten comes right after one.
The code starts by picking the number one. It wants to find the number that sits at a specific spot, called the k-th spot. To do this, it acts like a detective exploring a tree of branches. It looks at the current number and figures out how many other numbers are hiding underneath it, starting with that same digit followed by more numbers.
If the detective finds that the spot is hidden somewhere inside the current branch, it dives deeper by moving to the next level down. That is like multiplying by ten to see numbers like ten, one hundred, or one thousand. If the spot is not in that branch, the detective skips over all those numbers and moves to the next neighbor instead. By jumping between levels and neighbors, the code moves closer and closer to the exact spot until it finds the right number.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Rust | Go | Python | TS | |||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| FelixFan1122 | C# | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| FelixFan1122 | C# | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 2376: Count Special Integers
Solved On The Same Day
- problem 1073: Adding Two Negabinary Numbers
- problem 1117: Building H2O
- problem 2296: Design a Text Editor
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality