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

// Observation: the numbers from 1...10 and 10...100 are sorted.  That is, each [10^k...10^(k+1)-1] is sorted already.
// So, imagine these are buckets.  We would keep taking one from each bucket iteratively.
// Here *=10 moves the bucket forward and dividing moves the bucket backwards.
class Solution {
public:
    constexpr vector<int> lexicalOrder(const int range) {
        vector<int> res{};
        res.reserve(range);
        int currNum{1};
        for (std::size_t i{1}; i <= range; i++) {
            res.push_back(currNum);
            if (currNum * 10 <= range){
                currNum*=10;
            } else if (not willIncreaseFirstNumber(currNum) && currNum + 1 <= range) {
                currNum++;
            } else {
                // we need to go back to a previous bucket that won't cause a dumb overflow
                while (willIncreaseFirstNumber(currNum/10)){
                    currNum/=10;
                }
                currNum = (currNum / 10)+1;
            }
        }

        return res;
    }

private:
    // for instance, adding one to 19 gives 20 which overflows.
    // When ordering, for example, 1...35, we need the order to be 19, 2, 20.
    // Thus we must be careful when increasing the elemtn
    bool willIncreaseFirstNumber(const int num){
        return (num % 10) == 9;
    }
};
11631