Building a lexicographically increasing sequence of first n natural numbers in JavaScript


Problem

We are required to write a JavaScript function that takes in a number n and return an array containing first n natural number.

The only condition is that the numbers should be sorted lexicographically which means all the numbers starting with 1 should come before any starting with 2 or 3 or 4 and so on.

Example

Following is the code −

 Live Demo

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

Following is the console 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
]

Updated on: 17-Apr-2021

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements