Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Building a lexicographically increasing sequence of first n natural numbers in JavaScript
We are required to write a JavaScript function that takes in a number n and returns an array containing the first n natural numbers. The condition is that the numbers should be sorted lexicographically, which means all numbers starting with 1 should come before any starting with 2, 3, 4, and so on.
Understanding Lexicographical Ordering
Lexicographical ordering treats numbers as strings. For example, "10" comes before "2" because "1" comes before "2" alphabetically. This creates the sequence: 1, 10, 11, 12, ..., 19, 2, 20, 21, ..., etc.
Example Implementation
const num = 24;
const buildLexicographically = (num = 1) => {
const res = [];
const curr = num >= 9 ? 9 : num;
for (let i = 1; i <= curr; i++) {
res.push(i);
for (let j = i * 10; j <= num; j++) {
res.push(j);
if (j % 10 === 9) {
break;
}
}
}
return res;
};
console.log(buildLexicographically(num));
Output
[
1, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 2, 20, 21, 22, 23,
24, 3, 4, 5, 6, 7, 8, 9
]
How It Works
The algorithm uses a depth-first approach:
- For each digit from 1 to 9 (or up to num if num
- Add the digit itself to the result
- Then add all numbers starting with that digit (10, 11, 12... for digit 1)
- Stop when reaching numbers ending in 9 or exceeding num
Alternative Approach Using Sort
const buildLexicographicallySimple = (n) => {
const numbers = Array.from({length: n}, (_, i) => i + 1);
return numbers.sort((a, b) => String(a).localeCompare(String(b)));
};
console.log(buildLexicographicallySimple(24));
Output
[
1, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 2, 20, 21, 22, 23,
24, 3, 4, 5, 6, 7, 8, 9
]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Depth-First Approach | O(n) | O(n) | Complex |
| Sort Approach | O(n log n) | O(n) | Simple |
Conclusion
Lexicographical ordering treats numbers as strings for comparison. The depth-first approach is more efficient, while the sort approach is simpler to understand and implement.
