LeetCode 386, Medium. Topics: Depth-First Search, Trie. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 12 parametrized pytest cases, and a playground notebook:
Problem
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.
You must write an algorithm that runs in O(n) time and uses O(1) extra space.
Examples
Constraints
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026