Lexical Order

Lexical Order

Given an integer n, return the numbers 1 to n arranged in lexicographic (dictionary) order, where numbers are compared as strings.

lexicalOrder(n)

Input format: a single integer n. Output the numbers space-separated.

Examples

n=13   // → 1 10 11 12 13 2 3 4 5 6 7 8 9
n=2    // → 1 2

Walkthrough

Thinking it through

The brute-force approach: generate 1 through n, convert to strings, sort. That works but costs O(n log n) for the sort plus string overhead — more than needed for what's actually a structured ordering.

Seeing the tree hiding in the numbers

Lexicographic order compares numbers as strings. "1" is a prefix of "10"–"19", which are prefixes of "100"–"109", "110"–"119", and so on. Appending a digit produces a more specific string that still starts with the original — a tree, where each number's children are itself with one more digit (0–9) appended. The root level is 1 through 9 (no leading zeros).

Why depth-first, pre-order traversal gives lexicographic order

"1" comes before "10", before "100", before "11" — visit a number, then everything prefixed by it, before moving to the next sibling. That's exactly pre-order DFS: visit the node, recurse fully into each child in digit order, then return to the next sibling.

Building the algorithm

  1. For each starting digit 1–9 (while ≤ n), begin a traversal.
  2. Record the current number.
  3. Try extending by each digit 0–9, forming a child value. If it's still ≤ n, recurse; if it exceeds n, stop extending (larger digits only make it bigger).
  4. Once a node's valid children are exhausted, return to continue with the next sibling.

Why this beats generate-and-sort

The traversal visits each number once, already in order — no sort needed. Total work is O(n), not O(n log n). Some orderings that look like they need an explicit sort are actually implicit in a natural tree structure — spot that, and a simple traversal replaces the sort.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.