Find the n-th binary string in sorted order

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

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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 form (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 Index Binary String
0 000 aaa
1 001 aab
2 010 aba
3 011 abb
4 100 baa
5 101 bab
6 110 bba
7 111 bbb

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 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

 // Java Implementation of the above approach import java.io.*; import java.util.*; class Gfg {        // Function to return the nth string in the required sequence     static String obtain_str(int n)     {         // Length of the resultant string         int len = (int)Math.floor((Math.log(n + 1) / Math.log(2)));            // Relative Index         int rel_ind = n + 1 - (int)Math.pow(2, len);            int i = 0;         StringBuilder str = new StringBuilder();         for (i = 0; i < len; i++) {                // Initial string of length len consists of             // all a's since the list is sorted             str.append('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.setCharAt(i, 'b');             rel_ind /= 2;             i++;         }            // Reverse and return the string         str = str.reverse();         return str.toString();     }        // Driver funtion     public static void main(String args[])     {         int n = 11;         System.out.print(obtain_str(n));     } }

Python3

 # Python3 implementation of the # above approach     # from math lib import log2 function from math import log2    # Function to return the nth string  # in the required sequence  def obtain_str(n) :        # Length of the resultant string      length = int(log2(n + 1))         # Relative index      rel_ind = n + 1 - pow(2, length)        i = 0     string = ""             for i in range(length) :            # Initial string of length len consists          # of all a's since the list is sorted          string += 'a'        i = 0            string_list = list(string)            # Convert relative index to Binary      # form and set 0 = a and 1 = b      while (rel_ind > 0) :         if (rel_ind % 2 == 1) :              string_list[i] = 'b'                        rel_ind //= 2         i += 1            # Reverse and return the string      string_list.reverse()     string = "".join(string_list)            return string    # Driver Code  if __name__ == "__main__" :         n = 11     print(obtain_str(n))    # This code is contributed by Ryuga

PHP

 0)     {         if (\$rel_ind % 2 == 1)             \$str[\$i] = 'b';         \$rel_ind = (int)(\$rel_ind / 2);         \$i++;     }        // Reverse and return the string     return strrev(\$str); }    // Driver Code \$n = 11; echo obtain_str(\$n);    // This code is contributed  // by chandan_jnu ?>

Output:

baa

My Personal Notes arrow_drop_up If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : AnkitRai01, Chandan_Kumar

Article Tags :
Practice Tags :

1

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.