Find the Kth Locker Code in Dictionary Order Up to N

Last updated: November 29, 2026

Quick Overview

Amazon Locker codes are the integers 1 to n, but the kiosk lists them sorted as strings (1, 10, 100, 11, ...). Given n and k, return the kth code in that order without generating or sorting the whole list, for n up to 10^9.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Amazon Locker codes are the integers 1 to n, but the kiosk lists them sorted as strings (1, 10, 100, 11, ...). Given n and k, return the kth code in that order without generating or sorting the whole list, for n up to 10^9.

An Amazon onsite hard question about counting in an implicit 10-ary tree. The interviewer wants the prefix-step counting function and the walk that either skips a whole subtree or descends into it.

What the Interviewer Expects
  • Models dictionary order as preorder of a 10-ary prefix tree
  • Counts numbers under a prefix within n in O(log n)
  • Skips subtrees when count < k, descends otherwise
  • Achieves O(log^2 n) time
  • Handles k = 1 and prefixes near n
Key Topics to Cover
prefix tree
counting
lexicographic order
math
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Return the position of a given code instead of the code at a position.
  • What changes if codes are zero-padded to a fixed width?
  • How would you page through results 20 at a time efficiently?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: 1 <= k <= n <= 10^9. Output: the kth smallest of 1..n when compared as decimal strings. Generating all n strings is too slow and too large....

High-Level Design

Lexicographic order of 1..n is a preorder walk of a tree where the children of prefix p are p0 through p9 (and the roots are 1 through 9). To find the kth node, count how many numbers in [1, n] start ...


Submit Your Answer
Markdown supported