Find the K-th Shard ID in Dictionary Order Without Listing
Last updated: November 29, 2026
Quick Overview
Given n and k, return the k-th smallest integer in the range 1 to n under lexicographic (string) ordering, for n up to 10^9.
0
0
0 solved
Given n and k, return the k-th smallest integer in the range 1 to n under lexicographic (string) ordering, for n up to 10^9.
A Google onsite follow-up to the dictionary-order listing question, where n is too large to enumerate. The interviewer checks counting the size of a subtree in the implicit digit trie and skipping whole subtrees.
What the Interviewer Expects
- Model numbers as an implicit 10-ary trie
- Count numbers under a prefix level by level, capped by n
- Skip a subtree when k exceeds its size, else descend
- Handle the off-by-one of counting the prefix itself
- Achieve O(log^2 n) time
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you find the rank of a given number instead?
- What if the range is [lo, hi] rather than [1, n]?
- How would you adapt this to strings over a 26-letter alphabet with a length cap?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: n up to 10^9, 1 <= k <= n. Output: the k-th number in the sorted-as-strings order of 1..n....
High-Level Design
In the implicit trie, the subtree of prefix p contains p, p0..p9, p00..p99, and so on, all capped at n. Its size can be counted level by level: start with the interval [p, p+1), and at eac...