Construct a string of length L such that each substring of length X has exactly Y distinct letters
Last Updated :
16 Nov, 2021
Given the length of the string l, the length of the substring x and the number of distinct characters that a substring of length x must have are y, the task is to find a string of length l in which every substring of length x has y distinct characters.
Examples:
Input: l = 6, x = 5, y = 3
Output: abcabc
Explanation:
If we take a substring of the first five characters then the substring will be “abcab”.
There are exactly three distinct characters (a, b, c) in the substring.
Similarly, if we take any substring from the string of length 5 then it will have
exactly 3 distinct characters.
Input: l = 3, x = 1, y = 1
Output: aaa
Explanation:
If we take the substring of length 1 then it will have exactly 1 distinct character in it.
Approach:
To solve the problem mentioned above we follow the steps given below:
- Initialize a variable p as 97 which marks the ASCII value of lower case letter ‘a’.
- Keep incrementing the value of p till y characters.
- Then repeat the character from the first character till it’s length become equal to length of given string and return the final string.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void String( int l, int x, int y)
{
int p = 97;
for ( int j = 0; j < l ; j++)
{
char ans = ( char )(p + (j % y));
cout << ans;
}
}
int main ()
{
int l = 6;
int x = 5;
int y = 3;
String(l, x, y) ;
return 0;
}
|
Java
public class GFG {
static void string( int l, int x, int y){
int p = 97 ;
for ( int j = 0 ; j < l ; j++){
char ans = ( char )(p + (j % y));
System.out.print(ans);
}
}
public static void main (String[] args) {
int l = 6 ;
int x = 5 ;
int y = 3 ;
string(l, x, y) ;
}
}
|
Python3
def String(l, x, y):
p = 97
for j in range (l):
ans = chr (p + j % y)
print (ans, end = "")
l = 6
x = 5
y = 3
String(l, x, y)
|
C#
using System;
class GFG {
static void String( int l, int x, int y)
{
int p = 97;
for ( int j = 0; j < l; j++)
{
char ans = ( char )(p + (j % y));
Console.Write(ans);
}
}
public static void Main( string [] args)
{
int l = 6;
int x = 5;
int y = 3;
String(l, x, y);
}
}
|
Javascript
<script>
function string(l , x , y){
var p = 97;
for ( var j = 0; j < l ; j++){
var ans = String.fromCharCode(p + (j % y));
document.write(ans);
}
}
var l = 6;
var x = 5;
var y = 3;
string(l, x, y) ;
</script>
|
Time Complexity: O(l)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...