Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Count number of substrings of a string consisting of same characters
Next article icon

Generate a string of size N whose each substring of size M has exactly K distinct characters

Last Updated : 31 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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++




// C++ program to generate a string of size N
// whose each substring of size M
// has exactly K distinct characters
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to generate the string
string generateString(int N, int M, int K)
{
 
    // Declare empty string
    string s = "";
 
    // counter for M
    int cnt1 = 0;
 
    // counter for K
    int cnt2 = 0;
 
    // Loop to generate string size of N
    for (int i = 0; i < N; i++) {
        cnt1++;
        cnt2++;
 
        // Generating K distinct
        // letters one by one
        if (cnt1 <= M) {
            if (cnt2 <= K) {
                s = s + char(96 + cnt1);
            }
 
            // After generating b distinct letters,
            // append rest a-b letters as 'a'
            else {
                s = s + 'a';
            }
        }
 
        // Reset the counter value
        // and repeat the process
        else {
            cnt1 = 1;
            cnt2 = 1;
            s = s + 'a';
        }
    }
 
    // return final result string
    return s;
}
 
// Driver code
int main()
{
    int N = 7, M = 5, K = 3;
 
    cout << generateString(N, M, K) << endl;
 
    return 0;
}
 
 

Java




// Java program to generate a String of size N
// whose each subString of size M
// has exactly K distinct characters
import java.util.*;
class GFG{
 
// Function to generate the String
static String generateString(int N, int M, int K)
{
 
    // Declare empty String
    String s = "";
 
    // counter for M
    int cnt1 = 0;
 
    // counter for K
    int cnt2 = 0;
 
    // Loop to generate String size of N
    for (int i = 0; i < N; i++)
    {
        cnt1++;
        cnt2++;
 
        // Generating K distinct
        // letters one by one
        if (cnt1 <= M)
        {
            if (cnt2 <= K)
            {
                s = s + (char)(96 + cnt1);
            }
 
            // After generating b distinct letters,
            // append rest a-b letters as 'a'
            else
            {
                s = s + 'a';
            }
        }
 
        // Reset the counter value
        // and repeat the process
        else
        {
            cnt1 = 1;
            cnt2 = 1;
            s = s + 'a';
        }
    }
 
    // return final result String
    return s;
}
 
// Driver code
public static void main(String[] args)
{
    int N = 7, M = 5, K = 3;
 
    System.out.println(generateString(N, M, K));
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program to generate a string of size N
# whose each substring of size M
# has exactly K distinct characters
# Function to generate the string
def generateString(N, M, K):
 
    # Declare empty string
    s = ""
 
    # counter for M
    cnt1 = 0
 
    # counter for K
    cnt2 = 0
 
    # Loop to generate string size of N
    for i in range (N):
        cnt1 += 1
        cnt2 += 1
 
        # Generating K distinct
        # letters one by one
        if (cnt1 <= M):
            if (cnt2 <= K):
                s = s + chr(96 + cnt1)
             
            # After generating b distinct letters,
            # append rest a-b letters as 'a'
            else:
                s = s + 'a'
 
        # Reset the counter value
        # and repeat the process
        else:
            cnt1 = 1
            cnt2 = 1
            s = s + 'a'
 
    # return final result string
    return s
 
# Driver code
if __name__ == "__main__": 
    N = 7
    M = 5
    K = 3
    print (generateString(N, M, K))
     
# This code is contributed by Chitranayal
 
 

C#




// C# program to generate a String of
// size N whose each subString of size
// M has exactly K distinct characters
using System;
 
class GFG{
 
// Function to generate the String
static String generateString(int N, int M, int K)
{
 
    // Declare empty String
    String s = "";
 
    // Counter for M
    int cnt1 = 0;
 
    // Counter for K
    int cnt2 = 0;
 
    // Loop to generate String size of N
    for(int i = 0; i < N; i++)
    {
       cnt1++;
       cnt2++;
        
       // Generating K distinct
       // letters one by one
       if (cnt1 <= M)
       {
           if (cnt2 <= K)
           {
               s = s + (char)(96 + cnt1);
           }
            
           // After generating b distinct letters,
           // append rest a-b letters as 'a'
           else
           {
               s = s + 'a';
           }
       }
        
       // Reset the counter value
       // and repeat the process
       else
       {
           cnt1 = 1;
           cnt2 = 1;
           s = s + 'a';
       }
    }
     
    // Return readonly result String
    return s;
}
 
// Driver code
public static void Main(String[] args)
{
    int N = 7, M = 5, K = 3;
 
    Console.WriteLine(generateString(N, M, K));
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
 
// Javascript program to generate
// a String of size N
// whose each subString of size M
// has exactly K distinct characters
 
    // Function to generate the String
    function generateString(N,M,K)
    {
        // Declare empty string
    let s = "";
  
    // counter for M
    let cnt1 = 0;
  
    // counter for K
    let cnt2 = 0;
  
    // Loop to generate string size of N
    for (let i = 0; i < N; i++) {
        cnt1++;
        cnt2++;
  
        // Generating K distinct
        // letters one by one
        if (cnt1 <= M) {
            if (cnt2 <= K) {
                s = s + String.fromCharCode(96 + cnt1);
            }
  
            // After generating b distinct letters,
            // append rest a-b letters as 'a'
            else {
                s = s + 'a';
            }
        }
  
        // Reset the counter value
        // and repeat the process
        else {
            cnt1 = 1;
            cnt2 = 1;
            s = s + 'a';
        }
    }
  
    // return final result string
    return s;
    }
     
    // Driver code
    let N = 7, M = 5, K = 3;
    document.write( generateString(N, M, K))
     
     
    // This code is contributed
    // by avanitrachhadiya2155
     
</script>
 
 
Output
abcaaab 

Time complexity: O(N) 
Space complexity: O(1)



Next Article
Count number of substrings of a string consisting of same characters

D

divyeshrabadiya07
Improve
Article Tags :
  • Algorithms
  • Aptitude
  • Competitive Programming
  • Design Pattern
  • DSA
  • Strings
  • System Design
  • C-String-Question
Practice Tags :
  • Algorithms
  • Strings

Similar Reads

  • Count of substrings of given string with frequency of each character at most K
    Given a string str, the task is to calculate the number of substrings of the given string such that the frequency of each element of the string is almost K. Examples: Input: str = "abab", K = 1Output: 7Explanation: The substrings such that the frequency of each character is atmost 1 are "a", "b", "a
    6 min read
  • Count number of substrings of a string consisting of same characters
    Given a string. The task is to find out the number of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of su
    6 min read
  • Count of substrings of length K with exactly K-1 distinct characters
    Given a string consisting of lowercase characters and an integer k, the task is to count all substrings of length k which have exactly k-1 distinct characters. Example: Input: s = "abcc", k = 2 Output: 1Explanation: Substrings of length 2 are "ab", "bc" and "cc". Only "cc" has 2-1 = 1 distinct chara
    7 min read
  • Count odd length Substrings with median same as Kth character of String
    Given a string S of size N, the task is to find the number of substrings of odd lengths that have a median equal to the Kth character of the string. Examples: Input: S = "ecadgg", K = 4Output: 4Explanation: Character at 4th position in string is 'd'. Then there are 4 odd length substrings with 'd' a
    11 min read
  • Find distinct characters in distinct substrings of a string
    Given a string str, the task is to find the count of distinct characters in all the distinct sub-strings of the given string.Examples: Input: str = "ABCA" Output: 18 Distinct sub-stringsDistinct charactersA1AB2ABC3ABCA3B1BC2BCA3C1CA2 Hence, 1 + 2 + 3 + 3 + 1 + 2 + 3 + 1 + 2 = 18Input: str = "AAAB" O
    5 min read
  • Construct a string of length L such that each substring of length X has exactly Y distinct letters
    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: abc
    4 min read
  • Generate a String of having N*N distinct non-palindromic Substrings
    Given an even integer N, the task is to construct a string such that the total number of distinct substrings of that string that are not a palindrome equals N2. Examples: Input: N = 2 Output: aabb Explanation: All the distinct non-palindromic substrings are ab, abb, aab and aabb. Therefore, the coun
    4 min read
  • Count of Distinct strings possible by inserting K characters in the original string
    Given a string S and an integer K, the task is to find the total number of strings that can be formed by inserting exactly K characters at any position of the string S. Since the answer can be large, print it modulo 109+7.Examples: Input: S = "a" K = 1 Output: 51 Explanation: Since any of the 26 cha
    12 min read
  • Minimum value of K such that each substring of size K has the given character
    Given a string of lowercase letters S a character c. The task is to find minimum K such that every substring of length K contains the given character c. If there is no such K possible, return -1.Examples: Input: S = "abdegb", ch = 'b'Output: 4 Explanation:Consider the value of K as 4. Now, every sub
    12 min read
  • Check if a K-length substring exists having only 2 distinct characters, each with frequency greater than K/3
    Given a string S of lowercase alphabets and an integer K, the task is to find whether there exists a substring of length K having only 2 unique characters and the count of both of the characters must be greater than K/3. If such a string exists, print 'YES' else 'NO'. Examples: Input: "abbad", K = 4
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences