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 firstname.lastname@example.org. 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.
- 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