Print all possible strings of length k that can be formed from a set of n characters in C++

In this problem, we are given a set of characters and a positive integer k and we have to print all possible strings of length k that can be generated using the characters of the set.

Let’s take an example to understand the problem better −

Input: set = {‘x’, ‘y’, ‘z’} , k = 2
Output: xy, xz, yz

To solve this problem, we have to find all possible sequences that can be generated. For the set of size n, the total number of a possible string of length k will be nk (n^k). We will use a recursive call to generate the string which will start from empty string and adding character by character to it.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printKLengthString(char set[], string sequence, int n, int k) {
   if (k == 0){
   for (int i = 0; i < n; i++){
      string newSequence;
      printKLengthString(set, newSequence, n, k - 1);
int main() {
   char set[] = {'a', 'b'};
   int n = 2;
   int k = 3;
   printKLengthString(set, "", n, k);


aaa aab aba abb baa bab bba bbb