> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Lexicographical Numbers Python Solution

> Tested Python solution for LeetCode 386 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 386, [Medium](/catalog/medium). Topics: [Depth-First Search](/catalog/topics/depth-first-search), [Trie](/catalog/topics/trie). [View on LeetCode](https://leetcode.com/problems/lexicographical-numbers/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 386   # by problem number
lcpy gen -s lexicographical_numbers   # by problem name
```

## 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

```
Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
```

```
Input: n = 2
Output: [1,2]
```

### Constraints

* `1 <= n <= 5 * 10^4`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/lexicographical_numbers/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/lexicographical_numbers/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def lexical_order(self, n: int) -> list[int]:
        result: list[int] = []
        curr = 1
        for _ in range(n):
            result.append(curr)
            if curr * 10 <= n:
                curr *= 10
            else:
                while curr % 10 == 9 or curr + 1 > n:
                    curr //= 10
                curr += 1
        return result
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.