Find the String having each substring with exactly K distinct characters
Last Updated :
01 Nov, 2023
Given two integers N and K. The task is to find the string of length N, such that each substring of length greater than equal to K, has exactly K distinct characters.
Examples:
Input: N=10, K=3
Output : ABCABCABCA
Explanation: The output string has 3 distinct characters.
Input : N=20, K=7
Output : ABCDEFGABCDEFGABCDEF
Explanation: The output string has 7 distinct characters.
Approach:
To solve the problem mentioned above the main idea is to print distinct elements up to length K, and then repeat the same elements up to N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findString( int N, int K)
{
for ( int i = 0; i < N; i++) {
cout << char ( 'A' + i % K);
}
}
int main()
{
int N = 10;
int K = 3;
findString(N, K);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void findString( int N, int K)
{
for ( int i = 0 ; i < N; i++)
{
System.out.print(( char )( 'A' + i % K));
}
}
public static void main(String[] args)
{
int N = 10 ;
int K = 3 ;
findString(N, K);
}
}
|
Python3
def findString(N, K) :
for i in range (N) :
print ( chr ( ord ( 'A' ) + i % K),end = "");
if __name__ = = "__main__" :
N = 10 ;
K = 3 ;
findString(N, K);
|
C#
using System;
class GFG {
static void findString( int N, int K)
{
for ( int i = 0; i < N; i++)
{
Console.Write(( char )( 'A' + i % K));
}
}
public static void Main(String[] args)
{
int N = 10;
int K = 3;
findString(N, K);
}
}
|
Javascript
<script>
function findString(N, K)
{
for (let i = 0; i < N; i++)
{
document.write(String.fromCharCode( 'A' .charCodeAt() + i % K));
}
}
let N = 10;
let K = 3;
findString(N, K);
</script>
|
Time Complexity:O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...