Given an integer N. The task is to generate a string of length N, such that each substring of length K has exactly P distinct letters.
Note : P can be at least 1 and at most min(K, 26).
Examples :
Input : n = 10, k = 5, p = 3 Output : abcabcabca Input : n = 6, k = 3, p = 2 Output : ababab
Approach :
The solution to the problem can be found by observing the pattern.
If we represent the characters as numbers then the answer will look like, 1,2,3,…,p,1,2,3,…p,… . There is no substring containing more than P distinct characters and each substring of length K contains exactly P distinct characters because of the condition P \(\le\) K .
Implementation :
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// function to generate the string
string smallestString(int n, int k, int p){
string res = "";
for (int i = 0; i < n; ++i) {
res += char('a' + i % p);
}
return res;
}
int main() {
int n = 10, k = 5, p = 3;
cout << smallestString(n, k, p);
return 0;
}
Output :
abcabcabca
Time Complexity : O(N)