Skip to content
Related Articles

Related Articles

Find the n-th binary string in sorted order
  • Difficulty Level : Easy
  • Last Updated : 27 Jan, 2020

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




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

C#




// C# Implementation of the above approach
using System;
using System.Text;
  
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[i]='b';
            rel_ind /= 2;
            i++;
        }
  
        // Reverse and return the string
        return reverse(str.ToString());
    }
      
    static String reverse(String input) 
    {
        char[] a = input.ToCharArray();
        int l, r = a.Length - 1;
        for (l = 0; l < r; l++, r--) 
        {
            char temp = a[l];
            a[l] = a[r];
            a[r] = temp;
        }
        return String.Join("", a);
    }
      
    // Driver funtion
    public static void Main(String []args)
    {
        int n = 11;
        Console.Write(obtain_str(n));
    }
}
  
// This code is contributed by PrinciRaj1992

PHP




<?php
// PHP implementation of the above approach
  
// Function to return the nth string 
// in the required sequence
function obtain_str($n)
{
  
    // Length of the resultant string
    $len = (int)(log($n + 1) / log(2));
  
    // Relative index
    $rel_ind = $n + 1 - pow(2, $len);
  
    $i = 0;
    $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 = (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

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :