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, …
Input: n = 6
Input: n = 11
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:
Hence the string present at 11th index (relative index 4) is “baa”
Below is the implementation of the above approach:
if ($rel_ind % 2 == 1)
$str[$i] = ‘b’;
$rel_ind = (int)($rel_ind / 2);
// Reverse and return the string
// Driver Code
$n = 11;
// This code is contributed
// by chandan_jnu
- Find the winner of a game where scores are given as a binary string
- Print all permutations in sorted (lexicographic) order
- Find i'th Index character in a binary string obtained after n iterations
- Count 1's in a sorted binary array
- Python | Check if a given string is binary string or not
- Find the index of first 1 in a sorted array of 0's and 1's
- Find a Symmetric matrix of order N that contain integers from 0 to N-1 and main diagonal should contain only 0's
- Find the longest sub-string which is prefix, suffix and also present inside the string
- Convert String into Binary Sequence
- Count of substrings of a binary string containing K ones
- Check if all the 1's in a binary string are equidistant or not
- Check divisibility of binary string by 2^k
- Check if a binary string contains consecutive same or not
- Construct a binary string following the given constraints
- Number of substrings with odd decimal value in a binary string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.