The Wayback Machine - https://web.archive.org/web/20240927155948/https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
Open In App

Permutations of given String

Last Updated : 18 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string S, the task is to write a program to print all permutations of a given string. 

A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length N has N! permutations. 

Examples:

Input: S = “ABC”
Output: “ABC”, “ACB”, “BAC”, “BCA”, “CBA”, “CAB”

Input: S = “XY”
Output: “XY”, “YX”

Print permutations of a given string using backtracking:

Recursion Tree for permutations of string "ABC"

Recursion Tree for permutations of string “ABC”

Follow the given steps to solve the problem:

  • Create a function permute() with parameters as input string and starting index of the string
  • Call this function with values input string and starting index, idx as 0
    • In this function, if idx becomes size of the string then print the same string
      • Else run a for loop from idx to size – 1 and swap the current element in the for loop with the s[idx]
      • Then again call this same function by increasing the value of idx by 1
      • After that again swap the previously swapped values to initiate backtracking

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to print permutations of the string
// This function takes two parameters:
// 1. String
// 2. Starting index of the string.
void permuteRec(string& s, int idx)
{
    // Base case
    if (idx == s.size() - 1) {
        cout << s << endl;
        return;
    }

    for (int i = idx; i < s.size(); i++) {
      
        // Swapping 
        swap(s[idx], s[i]);

        // First idx+1 characters fixed
        permuteRec(s, idx + 1);

        // Backtrack
        swap(s[idx], s[i]);
    }
}

// Wrapper function
void permute(string& s) {
    permuteRec(s, 0);
}

int main(){
    string s = "ABC";
    permute(s);
    return 0;
}
C
#include <stdio.h>
#include <string.h>

// Function to swap two characters
void swap(char* x, char* y) {
    char temp = *x;
    *x = *y;
    *y = temp;
}

// Function to print permutations of the string
// This function takes two parameters:
// 1. String
// 2. Starting index of the string.
void permuteRec(char* str, int idx, int n) {
  
    // Base case
    if (idx == n - 1) {
        printf("%s\n", str);
        return;
    }

    for (int i = idx; i < n; i++) {
      
        // Swapping
        swap(&str[idx], &str[i]);

        // First idx+1 characters fixed
        permuteRec(str, idx + 1, n);

        // Backtrack
        swap(&str[idx], &str[i]);
    }
}

// Wrapper function
void permute(char* str) {
    int n = strlen(str);
    permuteRec(str, 0, n);
}

int main() {
    char str[] = "ABC";
    permute(str);
    return 0;
}
Java
import java.util.*;

class GfG {

    // Function to print permutations of the string
    // This function takes two parameters:
    // 1. String
    // 2. Starting index of the string.
    static void permuteRec(StringBuilder s, int idx) {
      
        // Base case
        if (idx == s.length() - 1) {
            System.out.println(s);
            return;
        }

        for (int i = idx; i < s.length(); i++) {
          
            // Swapping 
            swap(s, idx, i);

            // First idx+1 characters fixed
            permuteRec(s, idx + 1);

            // Backtrack
            swap(s, idx, i);
        }
    }

    // Wrapper function
    static void permute(String s) {
        permuteRec(new StringBuilder(s), 0);
    }

    // Helper function to swap characters in the StringBuilder
    static void swap(StringBuilder s, int i, int j) {
        char temp = s.charAt(i);
        s.setCharAt(i, s.charAt(j));
        s.setCharAt(j, temp);
    }

    public static void main(String[] args) {
        String s = "ABC";
        permute(s);
    }
}
Python
# Function to swap characters in a string
def swap(s, i, j):
    s = list(s)
    s[i], s[j] = s[j], s[i]
    return ''.join(s)

# Function to print permutations of the string
# This function takes two parameters:
# 1. String
# 2. Starting index of the string.
def permuteRec(s, idx):
  
    # Base case
    if idx == len(s) - 1:
        print(s)
        return
    
    for i in range(idx, len(s)):
      
        # Swapping
        s = swap(s, idx, i)

        # First idx+1 characters fixed
        permuteRec(s, idx + 1)

        # Backtrack
        s = swap(s, idx, i)

# Wrapper function
def permute(s):
    permuteRec(s, 0)

# Driver code
s = "ABC"
permute(s)
C#
using System;

class GfG {

    // Function to swap characters in a string
    static string Swap(string s, int i, int j) {
        char[] charArray = s.ToCharArray();
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
        return new string(charArray);
    }

    // Function to print permutations of the string
    // This function takes two parameters:
    // 1. String
    // 2. Starting index of the string.
    static void PermuteRec(string s, int idx) {
      
        // Base case
        if (idx == s.Length - 1) {
            Console.WriteLine(s);
            return;
        }

        for (int i = idx; i < s.Length; i++) {
          
            // Swapping
            s = Swap(s, idx, i);

            // First idx+1 characters fixed
            PermuteRec(s, idx + 1);

            // Backtrack
            s = Swap(s, idx, i);
        }
    }

    // Wrapper function
    static void Permute(string s) {
        PermuteRec(s, 0);
    }

    public static void Main() {
        string s = "ABC";
        Permute(s);
    }
}
JavaScript
// Function to swap characters in a string
function swap(s, i, j) {
    let charArray = s.split('');
    let temp = charArray[i];
    charArray[i] = charArray[j];
    charArray[j] = temp;
    return charArray.join('');
}

// Function to print permutations of the string
// This function takes two parameters:
// 1. String
// 2. Starting index of the string.
function permuteRec(s, idx) {
    // Base case
    if (idx === s.length - 1) {
        console.log(s);
        return;
    }

    for (let i = idx; i < s.length; i++) {
    
        // Swapping
        s = swap(s, idx, i);

        // First idx+1 characters fixed
        permuteRec(s, idx + 1);

        // Backtrack
        s = swap(s, idx, i);
    }
}

// Wrapper function
function permute(s) {
    permuteRec(s, 0);
}

let s = "ABC";
permute(s);

Output
ABC
ACB
BAC
BCA
CBA
CAB

Time Complexity: O(N * N!) Note that there are N! permutations and it requires O(N) time to print a permutation.
Auxiliary Space: O(N)

Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.



Previous Article
Next Article

Similar Reads

Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
Generate all permutations of a given length such that every permutation has more or equals 1's than 0's in all prefixes of the permutation. Examples: Input: len = 4 Output: 1111 1110 1101 1100 1011 1010 Note that a permutation like 0101 can not be in output because there are more 0's from index 0 to 2 in this permutation. Input: len = 3 Output: 111
5 min read
Find Kth largest string from the permutations of the string with two characters
Given two integers N and K, the task is to find the lexicographically Kth largest string of size N from the set of strings containing only two characters 'x' and 'y', where character 'x' is present in the string (N - 2) times and the character 'y' is present only 2 times.Examples: Input: N = 4, K = 3 Output: yxxy Explanation: All the strings of siz
7 min read
Print all the palindromic permutations of given string in alphabetic order
Given a string str of size n. The problem is to print all the palindromic permutations of str in alphabetic order if possible else print "-1". Examples : Input : str = "aabb" Output : abba baab Input : malayalam Output : aalmymlaa aamlylmaa alamymala almayamla amalylama amlayalma laamymaal lamayamal lmaayaaml maalylaam malayalam mlaayaalm Prerequis
15+ min read
Check if given string can be formed by two other strings or their permutations
Given a string str and an array of strings arr[], the task is to check if the given string can be formed by any of the string pairs from the array or their permutations. Examples: Input: str = "amazon", arr[] = {"loa", "azo", "ft", "amn", "lka"} Output: Yes The chosen strings are "amn" and "azo" which can be rearranged as "amazon". Input: str = "ge
13 min read
Number of permutations of a string in which all the occurrences of a given character occurs together
Given a string 's' and a character 'c', the task is to find the number of permutations of the string in which all the occurrences of the character 'c' will be together (one after another). Examples : Input: Str = "AKA" ch = 'A' Output: 2 Explanation: All the unique permutations of AKA are : AKA, AAK and KAA 'A' comes consecutively only twice. Hence
9 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. Input : str = "BCD" Output : BCD, BDC, CDB, CBD, DC
11 min read
Python3 Program for Check if given string can be formed by two other strings or their permutations
Given a string str and an array of strings arr[], the task is to check if the given string can be formed by any of the string pair from the array or their permutations. Examples: Input: str = "amazon", arr[] = {"loa", "azo", "ft", "amn", "lka"} Output: Yes The chosen strings are "amn" and "azo" which can be rearranged as "amazon". Input: str = "gee
4 min read
Print all lexicographical greater permutations of a given string
Given a string S, print those permutations of string S which are lexicographically greater than S. If there is no such permutation of string, print -1. Examples: Input : BCA Output : CAB, CBA Explanation: Here, S = "BCA", and there are 2 strings "CAB, CBA" which are lexicographically greater than S. Input : CBA Output : -1 There is no string which
13 min read
Print all distinct permutations of a given string with duplicates
Given a string that may contain duplicates, write a function to print all permutations of given string such that no permutation is repeated in output.Examples: Input: str[] = "AB" Output: AB BA Input: str[] = "AA" Output: AA Input: str[] = "ABC" Output: ABC ACB BAC BCA CBA CAB Input: str[] = "ABA" Output: ABA AAB BAA Input: str[] = "ABCA" Output: A
15 min read
Permutations of a given string using STL
A permutation, also called an "arrangement number" or "order", is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Source: Mathword Below are the permutations of string ABC. "ABC", "ACB", "BAC", "BCA", "CBA", "CAB" We have discussed C implementation to prin
3 min read
Count possible permutations of given array satisfying the given conditions
Given an array, arr[] consisting of N distinct elements, the task is to count possible permutations of the given array that can be generated which satisfies the following properties: The two halves must be sorted.arr[i] must be less than arr[N / 2 + i] Note: N is always even and indexing starts from 0. Examples: Input: arr[] = {10, 20, 30, 40} Outp
6 min read
Minimize count of given operations required to make two given strings permutations of each other
Given two strings str1 and str2, the task is to count the minimum number of operations of the following three types on one of the two strings that are required to make str1 and str2 permutations of each other: Insert a character into the string.Remove a character from the string.Replace a character with another character from the string.Note: All t
13 min read
Check if a binary string contains all permutations of length k
Given a binary string and k, to check whether it's contains all permutations of length k or not. Examples: Input : Binary string 11001 k : 2 Output : Yes 11001 contains all possibilities of binary sequences with k = 2, 00, 01, 10, 11 Input : Binary string: 1001 k : 2 Output: No 1001 does not contain all possibilities of binary sequences with k = 2.
13 min read
Number of unique permutations starting with 1 of a Binary String
Given a binary string composed of 0's and 1's. The task is to find the number of unique permutation of the string which starts with 1. Note: Since the answer can be very large, print the answer under modulo 109 + 7.Examples: Input : str ="10101001001" Output : 210 Input : str ="101110011" Output : 56 The idea is to first find the count of 1's and t
10 min read
Count of cyclic permutations having XOR with other binary string as 0
Given two binary strings [Tex]A [/Tex]and [Tex]B [/Tex]. Let [Tex]S [/Tex]be set of all the cyclic permutations of string [Tex]B [/Tex]. The task is to find how many strings in set [Tex]S [/Tex]when XORed with [Tex]A [/Tex]give [Tex]0 [/Tex]as result. Examples: Input: A = "101", B = "101" Output: 1 S = {"101", "011", "110"} Only "101" XOR "101" = 0
9 min read
Permutations of string such that no two vowels are adjacent
Given a string consisting of vowels and consonants. The task is to find the number of ways in which the characters of the string can be arranged such that no two vowels are adjacent to each other. Note: Given that No. of vowels <= No. of consonants. Examples: Input: str = "permutation" Output : 907200 Input: str = "geeksforgeeks" Output: 3175200
12 min read
Print first n distinct permutations of string using itertools in Python
Given a string with duplicate characters allowed, print first n permutations of given string such that no permutation is repeated. Examples: Input : string = "abcab", n = 10 Output : aabbc aabcb aacbb ababc abacb abbac abbca abcab abcba acabb Input : string = "okok", n = 4 Output : kkoo koko kook okko Approach: Python provides an inbuilt method to
2 min read
Print all permutations of a string in Java
Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. For instance, the words ‘bat’ and ‘tab’ represents two distinct permutation (or arrangements) of a similar three letter word. Examples: Input: str = "cd" Output: cd dc
3 min read
Print all the permutations of a string without repetition using Collections in Java
Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. A permutation should not have repeated strings in the output. Examples: Input: str = "aa" Output: aa Note that "aa" will be printed only once as duplicates are not all
2 min read
Distinct permutations of a string containing duplicates using HashSet in Java
Given a string str that may contain duplicate characters, the task is to print all the distinct permutations of the given string such that no permutation is repeated in the output. Examples: Input: str = "ABA" Output: ABA AAB BAA Input: str = "ABC" Output: ABC ACB BAC BCA CBA CAB Approach: An approach to generate all the permutations of a given str
2 min read
Count permutations possible by replacing '?' characters in a Binary String
Given a string S consisting of characters 0, 1, and '?', the task is to count all possible combinations of the binary string formed by replacing '?' by 0 or 1. Examples: Input: S = "0100?110"Output: 2Explanation: Replacing each '?'s with '1' and '0', the count of such strings formed will be equal to "01001110" and "01000110". Therefore, the total c
4 min read
Distinct Numbers obtained by generating all permutations of a Binary String
Given a binary string S, the task is to print all distinct decimal numbers that can be obtained by generating all permutations of the binary string. Examples: Input: S = "110"Output: {3, 5, 6}Explanation: All possible permutations are {"110", "101", "110", "101", "011", "011"}.Equivalent decimal numbers of these binary strings are {6, 5, 6, 5, 3, 3
8 min read
Print all palindrome permutations of a string
Given a string, we need to print all possible palindromes that can be generated using letters of that string. Examples: Input: str = "aabcb" Output: abcba bacab Input: str = "aabbcadad" Output: aabdcdbaa aadbcbdaa abadcdaba abdacadba adabcbada adbacabda baadcdaab badacadab bdaacaadb daabcbaad dabacabad dbaacaabdRecommended PracticePalindrome Patter
13 min read
All permutations of a string using iteration
A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation ( Source: Mathword ) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB We have discussed different recursive approaches to prin
4 min read
Time complexity of all permutations of a string
Time complexity of printing all permutations of a string. void perm(String str){ perm(str, ""); } void perm(String str, String prefix){ if(str.length() == 0){ System.out.println(prefix); } else{ for(int i = 0; i < str.length(); i++){ String rem = str.substring(0, i) + str.substring(i + 1); perm(rem, prefix + str.charAt(i)); } } } Understanding t
3 min read
Distinct permutations of the string | Set 2
Print all distinct permutations of a string having duplicates. Examples: Input : ABCAOutput : AABC AACB ABAC ABCA ACBA ACAB BAAC BACA BCAA CABA CAAB CBAAAn algorithm to print all distinct permutations has already been discussed here. Here we'll discuss one more approach to do the same. Recall first how we print permutations without any duplicates i
12 min read
Print k different sorted permutations of a given array
Given an array arr[] containing N integers, the task is to print k different permutations of indices such that the values at those indices form a non-decreasing sequence. Print -1 if it is not possible. Examples: Input: arr[] = {1, 3, 3, 1}, k = 3 Output: 0 3 1 2 3 0 1 2 3 0 2 1 For every permutation, the values at the indices form the following se
8 min read
Number of possible permutations when absolute difference between number of elements to the right and left are given
Given an array of N elements where each element i, the absolute difference between total elements to the right and left of it are given. Find the number of possible ordering of the actual array elements.Examples: Input : N = 5, arr[] = {2, 4, 4, 0, 2} Output : 4 There are four possible orders, as follows: 2, 1, 4, 5, 3 2, 5, 4, 1, 3 3, 1, 4, 5, 2 3
10 min read
Find the Number of Permutations that satisfy the given condition in an array
Given an array arr[] of size N, the task is to find the number of permutations in the array that follows the given condition: If K is the maximum element in the array, then the elements before K in the array should be in the ascending order and the elements after K in the array should be in the descending order. Examples: Input: arr[] = {1, 2, 3} O
12 min read
Print the two possible permutations from a given sequence
Given an array arr containing N positive integers, the task is to check if the given array can be dissociated into two permutations or not and print the permutations if possible. A sequence of M integers is called a permutation if it contains all integers from 1 to M exactly once. Examples: Input: arr[] = { 1, 2, 5, 3, 4, 1, 2 }, N = 7 Output: {1 2
12 min read