Permutations of given String (original) (raw)

Last Updated : 19 May, 2026

Given a string **s. Find all permutations of a given string. Return the permutations in lexicographically non-decreasing order.

**Examples:

**Input: s = "ABC"
**Output: ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]

**Input: s = "XY"
**Output: ["XY", "YX"]

**Input: s = "AAA"
**Output: "AAA", "AAA", "AAA", "AAA", "AAA", "AAA"

Try It Yourselfredirect icon

[Approach] Recursion and Swapping - O(n! * n) Time

Generate permutations by fixing one position at a time. First, we fix the first position and try every character in that position, then recursively generate all permutations for the remaining positions. After we fix the first position, we recursive repeat the process for the remaining string. Once we generate all permutations beginning with the current character, to bring the next character at its position in current string, we swap the next character, with the current character.

4

C++ `

#include #include #include using namespace std;

// Generate permutations using swapping void recurPermute(int index, string &s, vector &res) { if (index == s.size()) { res.push_back(s);
return; }

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

    // fix current position and recurse
    recurPermute(index + 1, s, res);

    // backtrack
    swap(s[index], s[i]);
}

}

vector permutation(string &s) { vector res;

recurPermute(0, s, res);

// sort lexicographically
sort(res.begin(), res.end());

return res;

}

int main() { string s = "AAB";

vector<string> res = permutation(s);

for (auto x : res) cout << x << " ";

return 0;

}

Java

import java.util.ArrayList; import java.util.Collections;

// Generate permutations using swapping public class Main { public static void recurPermute(int index, StringBuilder s, ArrayList res) { if (index == s.length()) { res.add(s.toString()); return; }

    for (int i = index; i < s.length(); i++) {
        char temp = s.charAt(index);
        s.setCharAt(index, s.charAt(i));
        s.setCharAt(i, temp);

        // fix current position and recurse
        recurPermute(index + 1, s, res);

        // backtrack
        temp = s.charAt(index);
        s.setCharAt(index, s.charAt(i));
        s.setCharAt(i, temp);
    }
}

public static ArrayList<String> permutation(String s) {
    ArrayList<String> res = new ArrayList<>();

    recurPermute(0, new StringBuilder(s), res);

    // sort lexicographically
    Collections.sort(res);

    return res;
}

public static void main(String[] args) {
    String s = "AAB";

    ArrayList<String> res = permutation(s);

    for (String x : res) System.out.print(x + " ");
}

}

Python

from typing import List

Generate permutations using swapping

def recurPermute(index, s, res): if index == len(s): res.append(''.join(s)) return

for i in range(index, len(s)):
    s[index], s[i] = s[i], s[index]

    # fix current position and recurse
    recurPermute(index + 1, s, res)

    # backtrack
    s[index], s[i] = s[i], s[index]

def permutation(s): res = []

s = list(s)

recurPermute(0, s, res)

# sort lexicographically
res.sort()

return res

if name == 'main': s = "AAB"

res = permutation(s)

for x in res: print(x, end=' ')

C#

using System; using System.Collections.Generic;

class GFG {

public void permutations(string str, int i, int n, List<string> v) {

    // Base condition
    if (i == n - 1) {
        v.Add(str);
        return;
    }

    // Generate permutations
    for (int j = i; j < n; j++) {

        // Swap characters
        char[] charArray = str.ToCharArray();
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;

        str = new string(charArray);

        permutations(str, i + 1, n, v);

        // Backtrack
        charArray = str.ToCharArray();
        temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;

        str = new string(charArray);
    }
}

public List<string> permutation(string s) {
    List<string> v = new List<string>();

    permutations(s, 0, s.Length, v);

    v.Sort();

    return v;
}

static void Main() {

    string s = "AAB";

    GFG obj = new GFG();

    var res = obj.permutation(s);

    foreach (var x in res) {
        Console.Write(x + " ");
    }
}

}

JavaScript

// Generate permutations using swapping function recurPermute(index, s, res) { if (index === s.length) { res.push(s.join('')); return; }

for (let i = index; i < s.length; i++) {
    [s[index], s[i]] = [s[i], s[index]];

    // fix current position and recurse
    recurPermute(index + 1, s, res);

    // backtrack
    [s[index], s[i]] = [s[i], s[index]];
}

}

function permutation(s) { const res = [];

s = s.split('');

recurPermute(0, s, res);

// sort lexicographically
res.sort();

return res;

}

const s = "AAB"; const res = permutation(s);

for (const x of res) console.log(x);

`

Output

AAB AAB ABA ABA BAA BAA

**Related articles: