Given N and K, print a string that has n characters. The string should have exactly k distinct characters and no adjacent positions.
Input : n = 5, k = 3 Output : abcab Explanation: 3 distinct character a, b, c and n length string. Input: 3 2 Output: aba Explanation: 2 distinct character 'a' and 'b' and n length string.
Consider the first k Latin letters. We will add them to the answer in the order, firstly, we add a, then b and so on. If letters are finished but the length of the answer is still less than the required one, then we start again adding letters from the beginning of the alphabet. We repeat this process until the length of the answer becomes n and print it once done.
Below is the implementation of the above approach
Time complexity : O(n)
This article is contributed by Raja Vikramaditya. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Return maximum occurring character in an input string
- Print all the duplicates in the input string
- Remove characters from the first string which are present in the second string
- Remove duplicates from a given string
- Print reverse of a string using recursion
- Write a program to print all permutations of a given string
- Divide a string in N equal parts
- Given a string, find its first non-repeating character
- Write a program to reverse an array or string
- Print list items containing all characters of a given word
- Reverse words in a given string
- Find the smallest window in a string containing all characters of another string
- Length of the longest substring without repeating characters
- Print all permutations with repetition of characters
- Interleaving of two given strings with no common characters
- Lexicographic rank of a string
- An in-place algorithm for String Transformation
- Count words in a given string
- String matching where one string contains wildcard characters
- Remove "b" and "ac" from a given string