386: Lexicographical-Numbers
Medium


table of contents

They be recycling daily questions already??!??!? (this was the daily question on 21/09/2024)

This question is just a simple recursion problem. You can see that in the example provided with n = 13 we get:

as the lexicographical order.

In it, it hints that the recursion equation should be, for any given i, we should have a function that iterates through all the possible digits in the ones column. Example:

Then, during this recursive function, while we iterate through all the possible digits in the ones column.

code

class Solution {
public:
    void addLexicographicalSmallest(vector<int>& ans, int current, int n) {
        for (int i = current; i <= min(current + 9, n); ++i) {
            ans.push_back(i);
            if ((i * 10) <= n) {
                addLexicographicalSmallest(ans, i*10, n);
            }
        }
    }
    vector<int> lexicalOrder(int n) {
        vector<int> ans;
        for (int i = 1; i <= min(9, n); ++i) {
            ans.push_back(i);
            if ((i * 10) <= n) {
                addLexicographicalSmallest(ans, i*10, n);
            }
        }
        return ans;
    }
};

complexity

time taken