Given 3 positive integers N, M, and K. the task is to construct a string of length N consisting of lowercase letters such that each substring of length M having exactly K distinct letters.
Examples:
Input: N = 5, M = 2, K = 2
Output: abade
Explanation:
Each substring of size 2 “ab”, “ba”, “ad”, “de” have 2 distinct letters.
Input: N = 7, M = 5, K = 3
Output: abcaaab
Explanation:
Each substring of size 5 “tleel”, “leelt”, “eelte” have 3 distinct letters.
Approach: In a string of size N, every substring of size M must contain exactly K distinct letters-
- Construct a string having K distinct alphabets starting from ‘a’ to ‘z’ up to the size of M and put the rest of letters like ‘a’..
- Since we have generated a string of size M with K distinct value. Now, keep repeating it till we reach string size of N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string generateString( int N, int M, int K)
{
string s = "" ;
int cnt1 = 0;
int cnt2 = 0;
for ( int i = 0; i < N; i++) {
cnt1++;
cnt2++;
if (cnt1 <= M) {
if (cnt2 <= K) {
s = s + char (96 + cnt1);
}
else {
s = s + 'a' ;
}
}
else {
cnt1 = 1;
cnt2 = 1;
s = s + 'a' ;
}
}
return s;
}
int main()
{
int N = 7, M = 5, K = 3;
cout << generateString(N, M, K) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static String generateString( int N, int M, int K)
{
String s = "" ;
int cnt1 = 0 ;
int cnt2 = 0 ;
for ( int i = 0 ; i < N; i++)
{
cnt1++;
cnt2++;
if (cnt1 <= M)
{
if (cnt2 <= K)
{
s = s + ( char )( 96 + cnt1);
}
else
{
s = s + 'a' ;
}
}
else
{
cnt1 = 1 ;
cnt2 = 1 ;
s = s + 'a' ;
}
}
return s;
}
public static void main(String[] args)
{
int N = 7 , M = 5 , K = 3 ;
System.out.println(generateString(N, M, K));
}
}
|
Python3
def generateString(N, M, K):
s = ""
cnt1 = 0
cnt2 = 0
for i in range (N):
cnt1 + = 1
cnt2 + = 1
if (cnt1 < = M):
if (cnt2 < = K):
s = s + chr ( 96 + cnt1)
else :
s = s + 'a'
else :
cnt1 = 1
cnt2 = 1
s = s + 'a'
return s
if __name__ = = "__main__" :
N = 7
M = 5
K = 3
print (generateString(N, M, K))
|
C#
using System;
class GFG{
static String generateString( int N, int M, int K)
{
String s = "" ;
int cnt1 = 0;
int cnt2 = 0;
for ( int i = 0; i < N; i++)
{
cnt1++;
cnt2++;
if (cnt1 <= M)
{
if (cnt2 <= K)
{
s = s + ( char )(96 + cnt1);
}
else
{
s = s + 'a' ;
}
}
else
{
cnt1 = 1;
cnt2 = 1;
s = s + 'a' ;
}
}
return s;
}
public static void Main(String[] args)
{
int N = 7, M = 5, K = 3;
Console.WriteLine(generateString(N, M, K));
}
}
|
Javascript
<script>
function generateString(N,M,K)
{
let s = "" ;
let cnt1 = 0;
let cnt2 = 0;
for (let i = 0; i < N; i++) {
cnt1++;
cnt2++;
if (cnt1 <= M) {
if (cnt2 <= K) {
s = s + String.fromCharCode(96 + cnt1);
}
else {
s = s + 'a' ;
}
}
else {
cnt1 = 1;
cnt2 = 1;
s = s + 'a' ;
}
}
return s;
}
let N = 7, M = 5, K = 3;
document.write( generateString(N, M, K))
</script>
|
Time complexity: O(N)
Space complexity: O(1)