Lexicographically smallest string of maximum length made up of first K alphabets that does not contain any repeating substring
Given a positive integer K, the task is to find lexicographically the smallest string that can be generated by using the first K lowercase alphabets such that no substring of length at least 2 is repeated in the generated string.
Input: K = 3
In the string “aabacbbcca”, all possible substrings of length at least 2 is repeated more than once.
Input: K = 4
Approach: The given problem can be solved based on the following observations:
- If all substrings of length 2 are unique, then all substrings of length greater than 2 will also be unique.
- Hence, the maximum length string should contain all unique substrings of length 2 arrange in lexicographic order such that no 3 consecutive characters in the string are the same.
Follow the steps below to solve the problem:
- Initialize a string, say S as the empty string that stores the resultant string.
- Iterate over all the first K characters of the lowercase alphabet using the variable, say i and perform the following steps:
- Append the current character i to the string S.
- Iterate from the (i + 1)th character to the Kth character, and append the character i followed by character j to the string S.
- Add the character ‘a’ to the string S so that substring consisting of the last and the first alphabet is also present in the resultant string.
- After completing the above steps, print the string S as the resultant string.
Below is the implementation of the above approach:
Time Complexity: O(K2)
Auxiliary Space: O(K2)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.