# Lexicographical Numbers LeetCode Solution

Here, We see Lexicographical Numbers LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

# List of all LeetCode Solution

## Problem Statement

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]

## Lexicographical Numbers LeetCode SolutionC++

``````class Solution {
public:
void solve(int i, int n,vector<int> &v){
if(i>n) return;
v.push_back(i);
for(int j=0;j<=9;j++){
solve(i*10+j,n,v);
}
}
vector<int> lexicalOrder(int n) {
vector<int> ans;
for(int i=1;i<10;i++){
solve(i,n,ans);
}
return ans;
}
};```Code language: JavaScript (javascript)```

## Lexicographical Numbers SolutionJava

``````class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> list = new ArrayList<>();
String[] str = new String[n];
for(int i=1;i<=n;i++) str[i-1] = Integer.toString(i);
Arrays.sort(str);
return list;
}
}```Code language: PHP (php)```

## Lexicographical Numbers SolutionJavaScript

``````var lexicalOrder = function(n) {
const a = new Array(n)
for(let i = 0; i < n; i++){
a[i] = i + 1;
}
return a.sort()
};```Code language: JavaScript (javascript)```

## Lexicographical Numbers SolutionPython

``````class Solution(object):
def lexicalOrder(self, n):
top = 1
while top * 10 <= n:
top *= 10
def mycmp(a, b, top=top):
while a < top: a *= 10
while b < top: b *= 10
return -1 if a < b else b < a
return sorted(xrange(1, n+1), mycmp)``````
Scroll to Top