Find the n-th binary string in sorted order in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a positive number of 1. Our task is to find the Nth binary string in sorted order.

We need to find the Nth string in an infinite list of strings created using only two symbols a and b sorted in lexicographical order.

The list is −

a, b, aa, ab, ba, bb, aaa, aab, aba, …

Let’s take an example to understand the problem,

Input : N = 8
Output : aab

Solution Approach

A simple solution to the problem is by using loops to generate all n strings. And then return the Nth string. This solution does the work but cannot provide an effective solution in case of large value of N.

So, we will see another solution which can provide the solution in less time.

Another approach to solve the problem is by using a relative index for the string. Using the fact that the number of strings of length N can be generated using 2 symbols is 2N. The relative index can be used to find the binary form string.

          Relative index = N + 1 - 2( floor(log(N+1)) )

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
#define ll long long int
string findBinString(ll n){
   ll len = (int)log2(n + 1);
   int ri = n + 1 - pow(2, len);
   ll i = 0;
   string binString = "";
   for (i = 0; i < len; i++) {
      binString += 'a';
   }
   i = 0;
   while (ri > 0) {
      if (ri % 2 == 1)
         binString[i] = 'b';
      ri /= 2;
      i++;
   }
   reverse(binString.begin(), binString.end());
   return binString;
}
int main(){
   ll n = 245;
   cout<<"The "<<n<<"-th binary string in sorted order is "<<findBinString(n);
   return 0;
}

Output

The 245-th binary string in sorted order is bbbabba
raja
Updated on 24-Jan-2022 13:09:51

Advertisements