Generate all passwords from given character set
Last Updated :
25 Apr, 2023
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 repetitions 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 */
JavaScript
<script>
// JavaScript program to generate all passwords for given characters
// let cnt;
// Recursive helper function, adds/removes characters
// until len is reached
function generate(arr, i, s, len)
{
// base case
if (i == 0) // when len has been reached
{
// print it out
document.write(s + "<br/>");
// cnt++;
return;
}
// iterate through the array
for (let j = 0; j < len; j++)
{
// Create new string with next character
// Call generate again until string has
// reached its len
let appended = s + arr[j];
generate(arr, i - 1, appended, len);
}
return;
}
// function to generate all possible passwords
function crack(arr, len)
{
// call for all required lengths
for (let i = 1; i <= len; i++)
{
generate(arr, i, "", len);
}
}
// Driver Code
let arr = ['a', 'b', 'c'];
let len = arr.length;
crack(arr, len);
</script>
Outputa
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 n^1 + n^2 +..+ n^n , 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. Approach#2: Using itertools
The approach used in this code is to generate all possible passwords of length up to 'length' using the characters in the array 'arr'. The itertools.product() method is used to generate all possible combinations of length up to 'length' of the characters in 'arr', and the extend() method is used to add these combinations to the 'passwords' list.
Algorithm
1. Initialize an empty list 'passwords'.
2. For i in range(1, length+1):
a. Generate all possible combinations of length i of the characters in 'arr' using itertools.product() method.
b. Convert each combination to a string using the join() method.
c. Add these strings to the 'passwords' list using the extend() method.
3. Return the 'passwords' list.
Python3
import itertools
def generate_passwords(arr, length):
passwords = []
for i in range(1, length+1):
passwords.extend([''.join(x) for x in itertools.product(arr, repeat=i)])
return passwords
arr = ['a', 'b', 'c' ]
length = len(arr)
print(generate_passwords(arr, length))
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']
Time complexity: O(n^m), where n is the length of 'arr' and m is the maximum length of the password. This is because the itertools.product() method generates all possible combinations of length up to 'length' of the characters in 'arr', and there can be n^m such combinations.
Space complexity: O(n^m), because the 'passwords' list will contain n^m elements at most, and each element can have a length of up to m. Additionally, the itertools.product() method generates all possible combinations of length up to 'length' of the characters in 'arr', which can also take up space. However, the space used by itertools.product() is negligible compared to the space used by the 'passwords' list.
Similar Reads
Find smallest string with whose characters all given Strings can be generated
Given an array of strings arr[]. The task is to generate the string which contains all the characters of all the strings present in array and smallest in size. There can be many such possible strings and any one is acceptable. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanati
5 min read
Generate all possible combinations of at most X characters from a given array
Given an array arr[] consisting of N characters, the task is to generate all possible combinations of at most X elements ( 1 ? X ? N). Examples: Input: N = 3, X = 2, arr[] = {'a', 'b', 'a'}Output: a b c bc ca ab cb ac baExplanation: All possible combinations using 1 character is 3 {'a', 'b', 'c'}. A
6 min read
Minimum characters required to make a password strong
Given string str denoting a password, the task is to count the minimum characters that need to be added to make the password strong. A password is said to be strong if it satisfies the following criteria: It contains at least 8 characters.It contains at least one digit.It contains at least one lower
6 min read
Generate all permutations of a string that follow given constraints
Given a string, generate all permutations of it that do not contain 'B' after 'A', i.e., the string should not contain "AB" as a substring. Examples: Input : str = "ABC" Output : ACB, BAC, BCA, CBA Out of 6 permutations of "ABC", 4 follow the given constraint and 2 ("ABC" and "CAB") do not follow. I
11 min read
Generate Passwords of given length
Given an integer N, the task is to generate random passwords of length N of easy, medium and strong level each. Easy level Password: Consists of only numbers or letters. Medium level Password: Consists of Letters as well as numbers. Strong level Password - Consists of Letters, numbers, and/or specia
11 min read
Random password generator in C
In this article, we will discuss how to generate a random password of a given length consists of any characters. Approach: The below-given program involves basic concepts like variables, data types, array, loop, etc.Follow the below steps to solve this problem:Take the length of the password and dec
2 min read
Frequency of Characters in Alphabetical Order
Given a string s, the task is to print the frequency of each of the characters of s in alphabetical order.Example: Input: s = "aabccccddd" Output: a2b1c4d3 Since it is already in alphabetical order, the frequency of the characters is returned for each character. Input: s = "geeksforgeeks" Output: e4
9 min read
Remove all characters other than alphabets from string
Given a string consisting of alphabets and others characters, remove all the characters other than alphabets and print the string so formed. Examples: Input : $Gee*k;s..fo, r'Ge^eks?Output : GeeksforGeeks Input : P&ra+$BHa;;t*ku, ma$r@@s#in}ghOutput : PraBHatkumarsingh Recommended PracticeRemove
12 min read
Missing characters to make a string Pangram
Pangram is a sentence containing every letter in the English alphabet. Given a string, find all characters that are missing from the string, i.e., the characters that can make the string a Pangram. We need to print output in alphabetic order. Examples: Input : welcome to geeksforgeeksOutput : abdhij
8 min read
Generate a String from given Strings P and Q based on the given conditions
Given two strings P and Q, the task is to generate a string S satisfying the following conditions: Find S such that P is rearranged and Q is a substring in it.All the characters before Q in S should be smaller than or equal to the first character in Q and in lexicographic order.The rest of the chara
7 min read