386. Lexicographical Numbers LeetCode Solution
In this guide, you will get 386. Lexicographical Numbers LeetCode Solution with the best time and space complexity. The solution to Lexicographical Numbers problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Lexicographical Numbers solution in C++
- Lexicographical Numbers solution in Java
- Lexicographical Numbers solution in Python
- Additional Resources

Problem Statement of Lexicographical Numbers
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.
Example 1:
Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Example 2:
Input: n = 2
Output: [1,2]
Constraints:
1 <= n <= 5 * 104
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
386. Lexicographical Numbers LeetCode Solution in C++
class Solution {
public:
vector<int> lexicalOrder(int n) {
vector<int> 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;
}
};
/* code provided by PROGIEZ */
386. Lexicographical Numbers LeetCode Solution in Java
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> 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;
}
}
// code provided by PROGIEZ
386. Lexicographical Numbers LeetCode Solution in Python
class Solution:
def lexicalOrder(self, n: int) -> list[int]:
ans = []
curr = 1
while len(ans) < n:
ans.append(curr)
if curr * 10 <= n:
curr *= 10
else:
while curr % 10 == 9 or curr == n:
curr //= 10
curr += 1
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.