<p>Given an integer <code>n</code>, return all the numbers in the range <code>[1, n]</code> sorted in lexicographical order.</p>

<p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and uses <code>O(1)</code> extra space.&nbsp;</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 13
<strong>Output:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 2
<strong>Output:</strong> [1,2]
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>
</ul>

# nlogn
class Solution:
    def lexicalOrder(self, n: int) -> List[int]:
        return sorted([x for x in range(1, n+1)], key=lambda x: str(x))

# lc n. note shouldn't be recursive (must be O(1) space)
class Solution:
    def lexicalOrder(self, n):
        res = [1]
        while len(res) < n:
            cur = res[-1] * 10
            while cur > n:
                cur //= 10
                cur += 1
                while cur % 10 == 0:
                    cur //= 10
            res.append(cur)
        return res

# note dfs - violates O(1) space requirement
class Solution:
    def lexicalOrder(self, n):
        res = []
        def dfs(cur):
            if cur > n:
                return
            res.append(cur)
            cur *= 10
            for x in range(10):
                if cur + x > n:
                    return
                dfs(cur + x)
        for x in range(1, 10):
            dfs(x)
        return res
25100