Leetcode 386. Lexicographical Numbers
Given an integer n
, return 1 - n
in lexicographical order.
Example:
Input: 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
n
?
public List<Integer> lexicalOrder(int n)
.To achieve lexicographical order without sorting, a good approach is to utilize Depth-First Search (DFS). Starting from 1
and moving forward by always trying to append the next digit:
1
and go as deep as possible before incrementing the prefix.n
, recurse into x*10.n
and not ending with a 9
(allows the next increment), increment x by 1
.1
to 9
and perform a DFS on each.n
.import java.util.ArrayList;
import java.util.List;
public class LexicographicalNumbers {
public List<Integer> lexicalOrder(int n) {
List<Integer> result = new ArrayList<>();
for (int i = 1; i < 10; i++) {
dfs(i, n, result);
}
return result;
}
private void dfs(int current, int n, List<Integer> result) {
if (current > n) {
return;
}
result.add(current);
for (int i = 0; i < 10; i++) {
if (10 * current + i > n) {
return;
}
dfs(10 * current + i, n, result);
}
}
public static void main(String[] args) {
LexicographicalNumbers lexiNumbers = new LexicographicalNumbers();
int n = 13;
System.out.println(lexiNumbers.lexicalOrder(n)); // Output: [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
}
}
1
to n
is visited exactly once, resulting in an (O(n)) complexity.n
. Hence, for n
up to (10^5), the stack depth would handle up to 5 levels.This solution provides an efficient way to generate numbers in lexicographical order without the need to sort them explicitly.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?