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:
- 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
- Count of substrings of a binary string containing K ones
- Check divisibility of binary string by 2^k
- Construct a binary string following the given constraints
- Convert String into Binary Sequence
- Check if a binary string contains all permutations of length k
- Decimal representation of given binary string is divisible by 5 or not
- Counting even decimal value substrings in a binary string
- Number of substrings with odd decimal value in a binary string
- Maximum contiguous 1 possible in a binary string after k rotations
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.
Improved By : Ryuga