Permute a string by changing case

06 Jul, 2022
Print all permutations of a string keeping the sequence but changing cases.Examples:  
Input : ab
Output : AB Ab ab aB

Input : ABC
Output : abc Abc aBc ABc abC AbC aBC ABC
 
Method 1 (Naive) : Naive approach would be to traverse the whole string and for every character, consider two cases, (1) change case and recur (2) Do not change case and recur.
C++
Python3
Javascript
// CPP code to print all permutations// with respect to cases#include <bits/stdc++.h>using namespace std; // Function to generate permutationsvoid permute(string ip, string op){    // base case    if (ip.size() == 0) {        cout << op << " ";        return;    }    // pick lower and uppercase    char ch = tolower(ip[0]);    char ch2 = toupper(ip[0]);    ip = ip.substr(1);     permute(ip, op + ch);    permute(ip, op + ch2);} // Driver codeint main(){    string ip = "aB";    permute(ip, "");    return 0;}
# Python code to print all permutations# with respect to cases # function to generate permutations  def permute(ip, op):     #  base case    if len(ip) == 0:        print(op, end=" ")        return     #  pick lower and uppercase    ch = ip[0].lower()    ch2 = ip[0].upper()    ip = ip[1:]    permute(ip, op+ch)    permute(ip, op+ch2) # driver code  def main():    ip = "AB"    permute(ip, "")  main() # This Code is Contributed by Vivek Maddeshiya
<script> // JavaScript code to print all permutations// with respect to cases // Function to generate permutationsfunction permute(ip, op){    // base case    if(ip.length == 0){        document.write(op," ");        return;    }    // pick lower and uppercase    let ch = ip[0].toLowerCase();    let ch2 = ip[0].toUpperCase();    ip = ip.substring(1) ;     permute(ip, op + ch);    permute(ip, op + ch2);} // Driver code let ip = "aB" ;permute(ip,""); // This code is contributed by shinjanpatra </script>
ab aB Ab AB 
Note: Recursion will generate output in this order only. 
Time Complexity: O(nn) Auxiliary Space: O(n)
Method 2 (Better) For a string of length n there exists 2n maximum combinations. We can represent this as a bitwise operation. The same idea is discussed in Print all subsequences.Below is the implementation of above idea :  
C++
Java
Python
C#
PHP
Javascript
// CPP code to print all permutations// with respect to cases#include <bits/stdc++.h>using namespace std; // Function to generate permutationsvoid permute(string input){    int n = input.length();     // Number of permutations is 2^n    int max = 1 << n;     // Converting string to lower case    transform(input.begin(), input.end(), input.begin(),              ::tolower);    // Using all subsequences and permuting them    for (int i = 0; i < max; i++) {         // If j-th bit is set, we convert it to upper case        string combination = input;        for (int j = 0; j < n; j++)            if (((i >> j) & 1) == 1)                combination[j] = toupper(input.at(j));         // Printing current combination        cout << combination << " ";    }} // Driver codeint main(){    permute("ABC");    return 0;}
// Java program to print all permutations// with respect to cases public class PermuteString {    // Function to generate permutations    static void permute(String input)    {        int n = input.length();         // Number of permutations is 2^n        int max = 1 << n;         // Converting string to lower case        input = input.toLowerCase();         // Using all subsequences and permuting them        for (int i = 0; i < max; i++) {            char combination[] = input.toCharArray();             // If j-th bit is set, we convert it to upper            // case            for (int j = 0; j < n; j++) {                if (((i >> j) & 1) == 1)                    combination[j]                        = (char)(combination[j] - 32);            }             // Printing current combination            System.out.print(combination);            System.out.print("   ");        }    }     // Driver Program to test above function    public static void main(String[] args)    {        permute("ABC");    }} // This code is contributed by Sumit Ghosh
# Python code to print all permutations# with respect to cases # Function to generate permutations  def permute(inp):    n = len(inp)     # Number of permutations is 2^n    mx = 1 << n     # Converting string to lower case    inp = inp.lower()     # Using all subsequences and permuting them    for i in range(mx):        # If j-th bit is set, we convert it to upper case        combination = [k for k in inp]        for j in range(n):            if (((i >> j) & 1) == 1):                combination[j] = inp[j].upper()         temp = ""        # Printing current combination        for i in combination:            temp += i        print temp,  # Driver codepermute("ABC") # This code is contributed by Sachin Bisht
// C# program to print all permutations// with respect to casesusing System; class PermuteString {     // Function to generate    // permutations    static void permute(String input)    {        int n = input.Length;         // Number of permutations is 2^n        int max = 1 << n;         // Converting string        // to lower case        input = input.ToLower();         // Using all subsequences        // and permuting them        for (int i = 0; i < max; i++) {            char[] combination = input.ToCharArray();             // If j-th bit is set, we            // convert it to upper case            for (int j = 0; j < n; j++) {                if (((i >> j) & 1) == 1)                    combination[j]                        = (char)(combination[j] - 32);            }             // Printing current combination            Console.Write(combination);            Console.Write(" ");        }    }     // Driver Code    public static void Main() { permute("ABC"); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to print all permutations// with respect to cases // Function to generate permutationsfunction permute($input){    $n = strlen($input);         // Number of permutations is 2^n    $max = 1 << $n;         // Converting string to lower case    $input = strtolower($input);         // Using all subsequences and permuting them    for($i = 0; $i < $max; $i++)    {        $combination = $input;                 // If j-th bit is set, we convert        // it to upper case        for($j = 0; $j < $n; $j++)        {            if((($i >> $j) & 1) == 1)                $combination[$j] = chr(ord($combination[$j]) - 32);        }                 // Printing current combination        echo $combination . " ";    }} // Driver Codepermute("ABC"); // This code is contributed by mits?>
<script> // javascript program to print all permutations// with respect to cases  // Function to generate permutationsfunction permute(input){    var n = input.length;         // Number of permutations is 2^n    var max = 1 << n;         // Converting string to lower case    input = input.toLowerCase();         // Using all subsequences and permuting them    for(var i = 0;i < max; i++)    {        var combination = input.split('');                 // If j-th bit is set, we convert it to upper case        for(var j = 0; j < n; j++)        {            if(((i >> j) &  1) == 1)                combination[j] = String.fromCharCode(combination[j].charCodeAt(0)-32);        }                 // Printing current combination        document.write(combination.join(''));        document.write("   ");    }} // Driver Program to test above functionpermute("ABC"); // This code contributed by Princi Singh</script>
abc Abc aBc ABc abC AbC aBC ABC 
Time complexity :O(n*2n) , since we are running a nested loop of size n inside a loop of size 2n.Auxiliary Space :O(n)
Asked in : Facebook.This article is contributed by Aarti_Rathi and Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
nitin mittal
Mithun Kumar
Akanksha_Rai
princi singh
ankita_saini
prasanna1995
shinjanpatra
vivekmaddheshiya205
youmailmahibagi
rohitmishra051000
codewithrathi
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Minimum number of jumps to reach end
Write a program to reverse an array or string
Reverse a string in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Longest Common Subsequence | DP-4
Different Methods to Reverse a String in C++