String with P distinct letters in every substring of length K

Updated

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)

Comment
Mithlesh Upadhyay Published 3 Dec 2026 · 1 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials