Lexicographical Numbers in C++


Suppose we have an integer n. We have to return 1 to n in lexicographic order. So for example when 13 is given, then the output will be [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9].

To solve this, we will follow these steps −

  • define one array ret of size n

  • curr := 1

  • for i in range 0 to n – 1

    • ret[i] := curr

    • if curr * 10 <= n, then set curr := curr * 10

    • otherwise

      • if curr >= n, then curr := curr / 10

      • increase curr by 1

      • while curr is divisible by 10, then curr := curr / 10

  • return ret

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> lexicalOrder(int n) {
      vector <int> ret(n);
      int curr = 1;
      for(int i = 0; i < n; i++){
         ret[i] = curr;
         if(curr * 10 <= n){
            curr*= 10;
         } else {
            if(curr>= n)curr /= 10;
            curr += 1;
            while(curr % 10 == 0)curr/=10;
         }
      }
      return ret;
   }
};
   main(){
   Solution ob;
   print_vector(ob.lexicalOrder(20));
}

Input

20

Output

[1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 3, 4, 5, 6, 7, 8, 9, ]

Updated on: 02-May-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements