Given a set of characters generate all possible passwords from them. This means we should generate all possible permutations of words using the given characters, with repititions and also upto a given length.
Examples:
Input : arr[] = {a, b},
len = 2.
Output :
a b aa ab ba bb
The solution is to use recursion on the given character array. The idea is to pass all possible lengths and an empty string initially to a helper function. In the helper function we keep appending all the characters one by one to the current string and recur to fill the remaining string till the desired length is reached.
It can be better visualized using the below recursion tree:
(a, b)
/ \
a b
/ \ / \
aa ab ba bb
Following is the implementation of the above method.
C++
// C++ program to generate all passwords for given characters #include <bits/stdc++.h> using namespace std; // int cnt; // Recursive helper function, adds/removes characters // until len is reached void generate(char* arr, int i, string s, int len) { // base case if (i == 0) // when len has been reached { // print it out cout << s << "\n"; // cnt++; return; } // iterate through the array for (int j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len string appended = s + arr[j]; generate(arr, i - 1, appended, len); } return; } // function to generate all possible passwords void crack(char* arr, int len) { // call for all required lengths for (int i = 1; i <= len; i++) { generate(arr, i, "", len); } } // driver function int main() { char arr[] = { 'a', 'b', 'c' }; int len = sizeof(arr) / sizeof(arr[0]); crack(arr, len); //cout << cnt << endl; return 0; } // This code is contributed by Satish Srinivas. |
Java
// Java program to generate all passwords for given characters import java.util.*; class GFG { // int cnt; // Recursive helper function, adds/removes characters // until len is reached static void generate(char[] arr, int i, String s, int len) { // base case if (i == 0) // when len has been reached { // print it out System.out.println(s); // cnt++; return; } // iterate through the array for (int j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len String appended = s + arr[j]; generate(arr, i - 1, appended, len); } return; } // function to generate all possible passwords static void crack(char[] arr, int len) { // call for all required lengths for (int i = 1; i <= len; i++) { generate(arr, i, "", len); } } // Driver code public static void main(String[] args) { char arr[] = {'a', 'b', 'c'}; int len = arr.length; crack(arr, len); } } // This code has been contributed by 29AjayKumar |
Python 3
# Python3 program to # generate all passwords # for given characters # Recursive helper function, # adds/removes characters # until len is reached def generate(arr, i, s, len): # base case if (i == 0): # when len has # been reached # print it out print(s) return # iterate through the array for j in range(0, len): # Create new string with # next character Call # generate again until # string has reached its len appended = s + arr[j] generate(arr, i - 1, appended, len) return # function to generate # all possible passwords def crack(arr, len): # call for all required lengths for i in range(1 , len + 1): generate(arr, i, "", len) # Driver Code arr = ['a', 'b', 'c' ] len = len(arr) crack(arr, len) # This code is contributed by Smita. |
C#
// C# program to generate all passwords for given characters using System; class GFG { // int cnt; // Recursive helper function, adds/removes characters // until len is reached static void generate(char[] arr, int i, String s, int len) { // base case if (i == 0) // when len has been reached { // print it out Console.WriteLine(s); // cnt++; return; } // iterate through the array for (int j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len String appended = s + arr[j]; generate(arr, i - 1, appended, len); } return; } // function to generate all possible passwords static void crack(char[] arr, int len) { // call for all required lengths for (int i = 1; i <= len; i++) { generate(arr, i, "", len); } } // Driver code public static void Main(String[] args) { char []arr = {'a', 'b', 'c'}; int len = arr.Length; crack(arr, len); } } /* This code contributed by PrinciRaj1992 */ |
Output:
a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc caa cab cac cba cbb cbc cca ccb ccc
If we want to see the count of the words, we can uncomment the lines having cnt variable in the code. We can observe that it comes out to be
, where n = len. Thus the time complexity of the program is also
, hence exponential. We can also check for a particular password
while generating and break the loop and return if it is found. We can also include other symbols to be generated and if needed remove duplicates by preprocessing the input using a HashTable.
This article is contributed by Satish Srinivas. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Replace all occurrences of character X with character Y in given string
- Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
- Generate all unique partitions of an integer | Set 2
- Generate all possible sorted arrays from alternate elements of two given sorted arrays
- Generate all permutations of a string that follow given constraints
- Generate all binary strings without consecutive 1's
- Generate all cyclic permutations of a number
- Generate all the binary strings of N bits
- Generate all possible strings such that char at index i is either str1[i] or str2[i]
- Generate all N digit numbers having absolute difference as K between adjacent digits
- Generate all distinct subsequences of array using backtracking
- Generate all possible permutations of a Number divisible by N
- Count ways to generate N-length array with 0s, 1s, and 2s such that sum of all adjacent pairwise products is K
- Recursive program to generate power set
- Number of permutations of a string in which all the occurrences of a given character occurs together
- Generate a combination of minimum coins that sums to a given value
- Minimum cost to generate any permutation of the given string
- Remove all occurrences of a character in a string | Recursive approach
- Generate permutations with only adjacent swaps allowed
- Generate an Array in which count of even and odd sum sub-arrays are E and O respectively

