List Shard IDs One to N in Dictionary Order

Last updated: November 29, 2026

Quick Overview

Given n, return the integers 1 through n sorted as strings would sort (lexicographically), in O(n) time and O(1) extra space beyond the output.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

0

0

0 solved


Given n, return the integers 1 through n sorted as strings would sort (lexicographically), in O(n) time and O(1) extra space beyond the output.

A Google phone screen warm-up framed around listing shard directories named by number, where a file browser sorts them as strings. The interviewer looks for the implicit 10-ary trie preorder rather than converting and sorting strings.

What the Interviewer Expects
  • Recognize the numbers as an implicit trie of digits
  • Generate a preorder walk without building the trie
  • Move to the next sibling correctly when the last digit is 9 or the value exceeds n
  • Avoid O(n log n) string sorting
  • Explain constant extra space
Key Topics to Cover
implicit trie
preorder traversal
lexicographic order
iteration
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
  • How would you get only the k-th number without listing all?
  • How would you list them in dictionary order starting from a given value?
  • What if numbers are zero-padded?
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: integer n >= 1. Output: list of 1..n in lexicographic order, e.g. n = 13 gives [1, 10, 11, 12, 13, 2, 3, ..., 9]....

High-Level Design

Picture a trie where each number's children are 10x through 10x + 9. Dictionary order is a preorder traversal of that trie. We can walk it with a single integer cur. After visiting cur, try to...


Submit Your Answer
Markdown supported