Given a set of characters and a positive integer k, print all possible strings of length k that can be formed from the given set.
Examples:
Input:
set[] = {'a', 'b'}, k = 3
Output:
aaa
aab
aba
abb
baa
bab
bba
bbb
Input:
set[] = {'a', 'b', 'c', 'd'}, k = 1
Output:
a
b
c
d
For a given set of size n, there will be n^k possible strings of length k. The idea is to start from an empty output string (we call it prefix in following code). One by one add all characters to prefix. For every character added, print all possible strings with current prefix by recursively calling for k equals to k-1.Â
Below is the implementation of above idea :Â
C++
// C++ program to print all // possible strings of length k#include <bits/stdc++.h>using namespace std;Â Â Â Â Â Â
// The main recursive method// to print all possible // strings of length kvoid printAllKLengthRec(char set[], string prefix,                                    int n, int k){         // Base case: k is 0,    // print prefix    if (k == 0)    {        cout << (prefix) << endl;        return;    }Â
    // One by one add all characters     // from set and recursively     // call for k equals to k-1    for (int i = 0; i < n; i++)    {        string newPrefix;                 // Next character of input added        newPrefix = prefix + set[i];                 // k is decreased, because         // we have added a new character        printAllKLengthRec(set, newPrefix, n, k - 1);    }Â
}Â
void printAllKLength(char set[], int k,int n){Â Â Â Â printAllKLengthRec(set, "", n, k);}Â
// Driver Codeint main(){Â Â Â Â Â Â Â Â Â cout << "First Test" << endl;Â Â Â Â char set1[] = {'a', 'b'};Â Â Â Â int k = 3;Â Â Â Â printAllKLength(set1, k, 2);Â Â Â Â Â Â Â Â Â cout << "Second Test\n";Â Â Â Â char set2[] = {'a', 'b', 'c', 'd'};Â Â Â Â k = 1;Â Â Â Â printAllKLength(set2, k, 4);}Â
// This code is contributed // by Mohit kumar |
Java
// Java program to print all // possible strings of length kÂ
class GFG {Â Â Â Â Â // The method that prints all // possible strings of length k.// It is mainly a wrapper over // recursive function printAllKLengthRec()static void printAllKLength(char[] set, int k){Â Â Â Â int n = set.length; Â Â Â Â printAllKLengthRec(set, "", n, k);}Â
// The main recursive method// to print all possible // strings of length kstatic void printAllKLengthRec(char[] set,                                String prefix,                                int n, int k){         // Base case: k is 0,    // print prefix    if (k == 0)     {        System.out.println(prefix);        return;    }Â
    // One by one add all characters     // from set and recursively     // call for k equals to k-1    for (int i = 0; i < n; ++i)    {Â
        // Next character of input added        String newPrefix = prefix + set[i];                  // k is decreased, because         // we have added a new character        printAllKLengthRec(set, newPrefix,                                 n, k - 1);     }}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â System.out.println("First Test");Â Â Â Â char[] set1 = {'a', 'b'};Â Â Â Â int k = 3;Â Â Â Â printAllKLength(set1, k);Â Â Â Â Â Â Â Â Â System.out.println("\nSecond Test");Â Â Â Â char[] set2 = {'a', 'b', 'c', 'd'};Â Â Â Â k = 1;Â Â Â Â printAllKLength(set2, k); }} |
Python3
# Python 3 program to print all # possible strings of length k     # The method that prints all # possible strings of length k.# It is mainly a wrapper over # recursive function printAllKLengthRec()def printAllKLength(set, k):Â
    n = len(set)     printAllKLengthRec(set, "", n, k)Â
# The main recursive method# to print all possible # strings of length kdef printAllKLengthRec(set, prefix, n, k):         # Base case: k is 0,    # print prefix    if (k == 0) :        print(prefix)        returnÂ
    # One by one add all characters     # from set and recursively     # call for k equals to k-1    for i in range(n):Â
        # Next character of input added        newPrefix = prefix + set[i]                 # k is decreased, because         # we have added a new character        printAllKLengthRec(set, newPrefix, n, k - 1)Â
# Driver Codeif __name__ == "__main__":Â Â Â Â Â Â Â Â Â print("First Test")Â Â Â Â set1 = ['a', 'b']Â Â Â Â k = 3Â Â Â Â printAllKLength(set1, k)Â Â Â Â Â Â Â Â Â print("\nSecond Test")Â Â Â Â set2 = ['a', 'b', 'c', 'd']Â Â Â Â k = 1Â Â Â Â printAllKLength(set2, k)Â
# This code is contributed # by ChitraNayal |
C#
// C# program to print all // possible strings of length kusing System;Â
class GFG {Â Â Â Â Â // The method that prints all // possible strings of length k.// It is mainly a wrapper over // recursive function printAllKLengthRec()static void printAllKLength(char[] set, int k){Â Â Â Â int n = set.Length; Â Â Â Â printAllKLengthRec(set, "", n, k);}Â
// The main recursive method// to print all possible // strings of length kstatic void printAllKLengthRec(char[] set,                                String prefix,                                int n, int k){         // Base case: k is 0,    // print prefix    if (k == 0)     {        Console.WriteLine(prefix);        return;    }Â
    // One by one add all characters     // from set and recursively     // call for k equals to k-1    for (int i = 0; i < n; ++i)    {Â
        // Next character of input added        String newPrefix = prefix + set[i];                  // k is decreased, because         // we have added a new character        printAllKLengthRec(set, newPrefix,                                 n, k - 1);     }}Â
// Driver Codestatic public void Main (){Â Â Â Â Console.WriteLine("First Test");Â Â Â Â char[] set1 = {'a', 'b'};Â Â Â Â int k = 3;Â Â Â Â printAllKLength(set1, k);Â Â Â Â Â Â Â Â Â Console.WriteLine("\nSecond Test");Â Â Â Â char[] set2 = {'a', 'b', 'c', 'd'};Â Â Â Â k = 1;Â Â Â Â printAllKLength(set2, k); }}Â
// This code is contributed by Ajit. |
Javascript
<script>// Javascript program to print all // possible strings of length k  Â
    // The method that prints all     // possible strings of length k.    // It is mainly a wrapper over     // recursive function printAllKLengthRec()    function printAllKLength(set,k)    {        let n = set.length;         printAllKLengthRec(set, "", n, k);    }         // The main recursive method    // to print all possible     // strings of length k    function printAllKLengthRec(set,prefix,n,k)    {        // Base case: k is 0,        // print prefix        if (k == 0)         {            document.write(prefix+"<br>");            return;        }               // One by one add all characters         // from set and recursively         // call for k equals to k-1        for (let i = 0; i < n; ++i)        {                   // Next character of input added            let newPrefix = prefix + set[i];                            // k is decreased, because             // we have added a new character            printAllKLengthRec(set, newPrefix,                                     n, k - 1);         }    }         // Driver Code    document.write("First Test<br>");    let set1=['a', 'b'];    let k = 3;    printAllKLength(set1, k);         document.write("<br>Second Test<br>");    let set2 = ['a', 'b', 'c', 'd'];    k = 1;    printAllKLength(set2, k);          // This code is contributed by avanitrachhadiya2155     </script> |
Output:Â
First Test aaa aab aba abb baa bab bba bbb Second Test a b c d
Time complexity: O(nk)
Auxiliary Space: O(k)
The above solution is mainly a generalization of this post.
This article is contributed by Abhinav Ramana. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
