# 386. Lexicographical Numbers

• Time: $O(n)$
• Space: $O(n)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Solution { public: vector lexicalOrder(int n) { vector ans; int curr = 1; while (ans.size() < n) { ans.push_back(curr); if (curr * 10 <= n) { curr *= 10; } else { while (curr % 10 == 9 || curr == n) curr /= 10; ++curr; } } return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public List lexicalOrder(int n) { List ans = new ArrayList<>(); int curr = 1; while (ans.size() < n) { ans.add(curr); if (curr * 10 <= n) { curr *= 10; } else { while (curr % 10 == 9 || curr == n) curr /= 10; ++curr; } } return ans; } }