Open In App

Find the n-th binary string in sorted order

Last Updated : 01 Nov, 2023
Comments
Improve
Suggest changes
1 Like
Like
Report

Given a positive integer n, the task is to find the nth string in the following infinite list of all possible strings over two symbols a and b sorted lexicographically (Dictionary). 

a, b, aa, ab, ba, bb, aaa, aab, aba, abb, baa, bab, bba, bbb, aaaa, ... 
 

Examples:  

Input: n = 6 
Output: bb

Input: n = 11 
Output: baa 

A simple approach is to generate all strings up to n and then determine the nth string. However, the approach is not suitable for large values of n.

An efficient approach is based on the fact that the number of length k strings that can be generated using 2 symbols is 2k. Based on this we can calculate the relative index from the actual index(n) with respect to the length of the string in the list. The string at nth index can then be determined easily using binary form of the relative index as the list is sorted. The following formula is used for calculation, 

relative index = n + 1 - 2floor(log(n + 1)) 
 

Consider the following example:  

Let n = 11 then floor(log(n + 1)) = 3
This suggests that index n consists of a length 3 string and length 3 strings start from (23 - 1) = 7th index and 7th index contains the string "aaa". 
Therefore, relative index = 11 + 1 - 23 = 4
This is the index relative to 7. Now, the string at index n = 11 can be simply obtained from the binary interpretation of the relative index 4
Here 0 means a and 1 means b. The table below illustrates this: 
 

Relative IndexBinaryString
0000aaa
1001aab
2010aba
3011abb
4100baa
5101bab
6110bba
7111bbb


Hence the string present at 11th index (relative index 4) is "baa"

Below is the implementation of the above approach:

C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long int

// Function to return the nth string in the required sequence
string obtain_str(ll n)
{

    // Length of the resultant string
    ll len = (int)log2(n + 1);

    // Relative index
    ll rel_ind = n + 1 - pow(2, len);

    ll i = 0;
    string str = "";
    for (i = 0; i < len; i++) {

        // Initial string of length len consists of
        // all a's since the list is sorted
        str += 'a';
    }

    i = 0;

    // Convert relative index to Binary form and set
    // 0 = a and 1 = b
    while (rel_ind > 0) {
        if (rel_ind % 2 == 1)
            str[i] = 'b';
        rel_ind /= 2;
        i++;
    }

    // Reverse and return the string
    reverse(str.begin(), str.end());
    return str;
}

// Driver function
int main()
{
    ll n = 11;
    cout << obtain_str(n);

    return 0;
}
Java Python3 C# JavaScript PHP

Output
baa

Time complexity : O(logn)

Auxiliary Space: O(1)


Next Article

Similar Reads