Open In App

Print all permutations in sorted (lexicographic) order

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s, print all unique permutations of the string in lexicographically sorted order.

Examples:

Input: “ABC”
Output: [“ABC”, “ACB”, “BAC”, “BCA”, “CAB”, “CBA”]
Explanation: All characters are distinct, so there are 3! = 6 unique permutations, printed in sorted order.

Input: “AAA”
Output: [“AAA”]
Explanation: All characters are same, so only one unique permutation is possible.

Input: “YZ”
Output: [“YZ”, “ZY”]

[Approach 1] Using Recursion + Set – O(n*n!) Time and O(n) Space

The idea is to use same algorithm as used in Permutations of given String along with a set to make sure we get distinct items. We recursively generate all permutations by swapping each character with the current index l and exploring all branches. The thought process is to fix one character at a time and permute the rest using recursive calls. A set is used to automatically discard duplicates and maintain lexicographical order. Finally, the set is converted to an array for output.

C++
// C++ Code to print all permutations in lexicographical
// order using Naive Approach
#include <bits/stdc++.h>
using namespace std;

// Recursive function to generate all 
// unique permutations
void generatePermutation(string &s, int l, int r,
                             set<string> &perms) {
    if (l == r) {
        perms.insert(s);
        return;
    }

    for (int i = l; i <= r; i++) {
        
        // Swap current character with index l
        swap(s[l], s[i]);

        // Recurse for the rest of the string
        generatePermutation(s, l + 1, r, perms);

        // Backtrack to restore original string
        swap(s[l], s[i]);
    }
}

// Function to initiate recursive call and sort results
vector<string> findAllPermutation(string s) {
    set<string> perms;

    // Call recursive function
    generatePermutation(s, 0, s.size() - 1, perms);

    // Convert set to vector to return
    vector<string> result(perms.begin(), perms.end());

    return result;
}

void printArray(vector<string> &result) {
    cout << "[";
    for (int i = 0; i < result.size(); i++) {
        cout << "\"" << result[i] << "\"";
        if (i != result.size() - 1) {
            cout << ", ";
        }
    }
    cout << "]" << endl;
}

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

    // Get all sorted unique permutations
    vector<string> result = findAllPermutation(s);

    // Print the result
    printArray(result);

    return 0;
}
Java
// Java Code to print all permutations in lexicographical
// order using Naive Approach
import java.util.*;

class GfG {

    // Recursive function to generate all 
    // unique permutations
    static void generatePermutation(String s, int l, int r,
                                    Set<String> perms, char[] arr) {
        if (l == r) {
            perms.add(new String(arr));
            return;
        }

        for (int i = l; i <= r; i++) {

            // Swap current character with index l
            char temp = arr[l];
            arr[l] = arr[i];
            arr[i] = temp;

            // Recurse for the rest of the string
            generatePermutation(s, l + 1, r, perms, arr);

            // Backtrack to restore original string
            temp = arr[l];
            arr[l] = arr[i];
            arr[i] = temp;
        }
    }

    // Function to initiate recursive call and sort results
    static String[] findAllPermutation(String s) {
        Set<String> perms = new TreeSet<>();
        char[] arr = s.toCharArray();

        // Call recursive function
        generatePermutation(s, 0, s.length() - 1, perms, arr);

        // Convert set to array to return
        String[] result = perms.toArray(new String[0]);

        return result;
    }

    static void printArray(String[] result) {
        System.out.print("[");
        for (int i = 0; i < result.length; i++) {
            System.out.print("\"" + result[i] + "\"");
            if (i != result.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }

    public static void main(String[] args) {

        String s = "ABC";

        // Get all sorted unique permutations
        String[] result = findAllPermutation(s);

        // Print the result
        printArray(result);
    }
}
Python
# Python Code to print all permutations in lexicographical
# order using Naive Approach

def generatePermutation(s, l, r, perms):
    if l == r:
        perms.add("".join(s))
        return

    for i in range(l, r + 1):

        # Swap current character with index l
        s[l], s[i] = s[i], s[l]

        # Recurse for the rest of the string
        generatePermutation(s, l + 1, r, perms)

        # Backtrack to restore original string
        s[l], s[i] = s[i], s[l]

# Function to initiate recursive call and sort results
def findAllPermutation(s):
    perms = set()

    # Call recursive function
    generatePermutation(list(s), 0, len(s) - 1, perms)

    # Convert set to sorted list to return
    result = sorted(list(perms))

    return result

def printArray(result):
    print("[", end="")
    for i in range(len(result)):
        print(f'"{result[i]}"', end="")
        if i != len(result) - 1:
            print(", ", end="")
    print("]")

if __name__ == "__main__":

    s = "ABC"

    # Get all sorted unique permutations
    result = findAllPermutation(s)

    # Print the result
    printArray(result)
C#
// C# Code to print all permutations in lexicographical
// order using Naive Approach
using System;
using System.Collections.Generic;

class GfG {

    // Recursive function to generate all 
    // unique permutations
    static void generatePermutation(string s, int l, int r,
                                    SortedSet<string> perms, char[] arr) {
        if (l == r) {
            perms.Add(new string(arr));
            return;
        }

        for (int i = l; i <= r; i++) {

            // Swap current character with index l
            char temp = arr[l];
            arr[l] = arr[i];
            arr[i] = temp;

            // Recurse for the rest of the string
            generatePermutation(s, l + 1, r, perms, arr);

            // Backtrack to restore original string
            temp = arr[l];
            arr[l] = arr[i];
            arr[i] = temp;
        }
    }

    // Function to initiate recursive call and sort results
    static string[] findAllPermutation(string s) {
        SortedSet<string> perms = new SortedSet<string>();
        char[] arr = s.ToCharArray();

        // Call recursive function
        generatePermutation(s, 0, s.Length - 1, perms, arr);

        // Convert set to array to return
        string[] result = new string[perms.Count];
        perms.CopyTo(result);

        return result;
    }

    static void printArray(string[] result) {
        Console.Write("[");
        for (int i = 0; i < result.Length; i++) {
            Console.Write("\"" + result[i] + "\"");
            if (i != result.Length - 1) {
                Console.Write(", ");
            }
        }
        Console.WriteLine("]");
    }

    static void Main() {

        string s = "ABC";

        // Get all sorted unique permutations
        string[] result = findAllPermutation(s);

        // Print the result
        printArray(result);
    }
}
JavaScript
// JavaScript Code to print all permutations in lexicographical
// order using Naive Approach

function generatePermutation(s, l, r, perms) {
    if (l === r) {
        perms.add(s.join(""));
        return;
    }

    for (let i = l; i <= r; i++) {

        // Swap current character with index l
        [s[l], s[i]] = [s[i], s[l]];

        // Recurse for the rest of the string
        generatePermutation(s, l + 1, r, perms);

        // Backtrack to restore original string
        [s[l], s[i]] = [s[i], s[l]];
    }
}

// Function to initiate recursive call and sort results
function findAllPermutation(s) {
    let perms = new Set();

    // Call recursive function
    generatePermutation(s.split(""), 0, s.length - 1, perms);

    // Convert set to sorted array to return
    let result = Array.from(perms);
    result.sort();

    return result;
}

function printArray(result) {
    process.stdout.write("[");
    for (let i = 0; i < result.length; i++) {
        process.stdout.write(`"${result[i]}"`);
        if (i !== result.length - 1) {
            process.stdout.write(", ");
        }
    }
    process.stdout.write("]\n");
}

let s = "ABC";

// Get all sorted unique permutations
let result = findAllPermutation(s);

// Print the result
printArray(result);

Output
["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]

[Approach 2] Using Next Permutation Approach – O(n*n!) Time and O(1) Space

The idea is to generate lexicographical permutations by using the next permutation algorithm iteratively. We start by sorting the input string to get the smallest permutation. In each step, we find the next permutation by identifying a pivot point and swapping with its ceil, then reversing the suffix.

Steps to implement the above idea:

  • Sort the input string in non-decreasing order to begin from the smallest lexicographical permutation.
  • Initialize a result array and push the sorted string as the first valid permutation.
  • Use a loop to repeatedly call the nextPermutation function until it returns false.
  • In nextPermutation, find the rightmost character i where s[i] < s[i+1], indicating a possible next permutation.
  • Then find index j such that s[j] > s[i] and swap the characters at i and j.
  • Reverse the substring from i+1 to end to get the next higher lexicographical arrangement.
  • Continue pushing each updated string into the result array until all permutations are found.
C++
// C++ Code to print all permutations in lexicographical
// order using Next Permutation Approach
#include <bits/stdc++.h>
using namespace std;

// Function to compute the next lexicographical
// permutation of the string
bool nextPermutation(string &s) {

    int n = s.size();

    // Find the rightmost character which is
    // smaller than its next character
    int i = n - 2;
    while (i >= 0 && s[i] >= s[i + 1]) {
        i--;
    }

    // If no such character found, all permutations done
    if (i < 0) {
        return false;
    }

    // Find the ceiling of s[i]
    int j = n - 1;
    while (j > i && s[j] <= s[i]) {
        j--;
    }

    // Swap the found characters
    swap(s[i], s[j]);

    // Sort (reverse) the substring after index i
    reverse(s.begin() + i + 1, s.end());

    return true;
}

// Function to find all permutations using next permutation
vector<string> findAllPermutation(string s) {

    // Sort the string to start from smallest
    sort(s.begin(), s.end());

    vector<string> result;

    // Insert the first permutation
    result.push_back(s);

    // Generate all higher permutations
    while (nextPermutation(s)) {
        result.push_back(s);
    }

    return result;
}

void printArray(vector<string> &result) {
    cout << "[";
    for (int i = 0; i < result.size(); i++) {
        cout << "\"" << result[i] << "\"";
        if (i != result.size() - 1) {
            cout << ", ";
        }
    }
    cout << "]" << endl;
}

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

    // Get all sorted unique permutations
    vector<string> result = findAllPermutation(s);

    // Print the result
    printArray(result);

    return 0;
}
Java
// Java Code to print all permutations in lexicographical
// order using Next Permutation Approach
import java.util.*;

class GfG {

    // Function to compute the next lexicographical
    // permutation of the string
    static boolean nextPermutation(char[] s) {

        int n = s.length;

        // Find the rightmost character which is
        // smaller than its next character
        int i = n - 2;
        while (i >= 0 && s[i] >= s[i + 1]) {
            i--;
        }

        // If no such character found, all permutations done
        if (i < 0) {
            return false;
        }

        // Find the ceiling of s[i]
        int j = n - 1;
        while (j > i && s[j] <= s[i]) {
            j--;
        }

        // Swap the found characters
        char temp = s[i];
        s[i] = s[j];
        s[j] = temp;

        // Sort (reverse) the substring after index i
        reverse(s, i + 1, n - 1);

        return true;
    }

    static void reverse(char[] s, int left, int right) {
        while (left < right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }

    // Function to find all permutations using next permutation
    static String[] findAllPermutation(String str) {

        char[] s = str.toCharArray();
        Arrays.sort(s);

        ArrayList<String> result = new ArrayList<>();
        result.add(new String(s));

        // Generate all higher permutations
        while (nextPermutation(s)) {
            result.add(new String(s));
        }

        return result.toArray(new String[0]);
    }

    static void printArray(String[] result) {
        System.out.print("[");
        for (int i = 0; i < result.length; i++) {
            System.out.print("\"" + result[i] + "\"");
            if (i != result.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }

    public static void main(String[] args) {

        String s = "ABC";

        // Get all sorted unique permutations
        String[] result = findAllPermutation(s);

        // Print the result
        printArray(result);
    }
}
Python
# Python Code to print all permutations in lexicographical
# order using Next Permutation Approach

# Function to compute the next lexicographical
# permutation of the string
def nextPermutation(s):

    n = len(s)

    # Find the rightmost character which is
    # smaller than its next character
    i = n - 2
    while i >= 0 and s[i] >= s[i + 1]:
        i -= 1

    # If no such character found, all permutations done
    if i < 0:
        return False

    # Find the ceiling of s[i]
    j = n - 1
    while j > i and s[j] <= s[i]:
        j -= 1

    # Swap the found characters
    s[i], s[j] = s[j], s[i]

    # Sort (reverse) the substring after index i
    s[i + 1:] = reversed(s[i + 1:])

    return True

# Function to find all permutations using next permutation
def findAllPermutation(s):

    s = sorted(list(s))

    result = []

    # Insert the first permutation
    result.append("".join(s))

    # Generate all higher permutations
    while nextPermutation(s):
        result.append("".join(s))

    return result

def printArray(result):
    print("[", end="")
    for i in range(len(result)):
        print(f"\"{result[i]}\"", end="")
        if i != len(result) - 1:
            print(", ", end="")
    print("]")

if __name__ == "__main__":

    s = "ABC"

    # Get all sorted unique permutations
    result = findAllPermutation(s)

    # Print the result
    printArray(result)
C#
// C# Code to print all permutations in lexicographical
// order using Next Permutation Approach
using System;
using System.Collections.Generic;

class GfG {

    // Function to compute the next lexicographical
    // permutation of the string
    static bool nextPermutation(char[] s) {

        int n = s.Length;

        // Find the rightmost character which is
        // smaller than its next character
        int i = n - 2;
        while (i >= 0 && s[i] >= s[i + 1]) {
            i--;
        }

        // If no such character found, all permutations done
        if (i < 0) {
            return false;
        }

        // Find the ceiling of s[i]
        int j = n - 1;
        while (j > i && s[j] <= s[i]) {
            j--;
        }

        // Swap the found characters
        char temp = s[i];
        s[i] = s[j];
        s[j] = temp;

        // Sort (reverse) the substring after index i
        Array.Reverse(s, i + 1, n - i - 1);

        return true;
    }

    // Function to find all permutations using next permutation
    static string[] findAllPermutation(string str) {

        char[] s = str.ToCharArray();
        Array.Sort(s);

        List<string> result = new List<string>();
        result.Add(new string(s));

        // Generate all higher permutations
        while (nextPermutation(s)) {
            result.Add(new string(s));
        }

        return result.ToArray();
    }

    static void printArray(string[] result) {
        Console.Write("[");
        for (int i = 0; i < result.Length; i++) {
            Console.Write("\"" + result[i] + "\"");
            if (i != result.Length - 1) {
                Console.Write(", ");
            }
        }
        Console.WriteLine("]");
    }

    static void Main() {

        string s = "ABC";

        // Get all sorted unique permutations
        string[] result = findAllPermutation(s);

        // Print the result
        printArray(result);
    }
}
JavaScript
// JavaScript Code to print all permutations in lexicographical
// order using Next Permutation Approach

// Function to compute the next lexicographical
// permutation of the string
function nextPermutation(s) {

    let n = s.length;

    // Find the rightmost character which is
    // smaller than its next character
    let i = n - 2;
    while (i >= 0 && s[i] >= s[i + 1]) {
        i--;
    }

    // If no such character found, all permutations done
    if (i < 0) {
        return false;
    }

    // Find the ceiling of s[i]
    let j = n - 1;
    while (j > i && s[j] <= s[i]) {
        j--;
    }

    // Swap the found characters
    [s[i], s[j]] = [s[j], s[i]];

    // Sort (reverse) the substring after index i
    let left = i + 1, right = n - 1;
    while (left < right) {
        [s[left], s[right]] = [s[right], s[left]];
        left++;
        right--;
    }

    return true;
}

// Function to find all permutations using next permutation
function findAllPermutation(str) {

    let s = str.split('').sort();

    let result = [];

    // Insert the first permutation
    result.push(s.join(""));

    // Generate all higher permutations
    while (nextPermutation(s)) {
        result.push(s.join(""));
    }

    return result;
}

function printArray(result) {
    process.stdout.write("[");
    for (let i = 0; i < result.length; i++) {
        process.stdout.write("\"" + result[i] + "\"");
        if (i != result.length - 1) {
            process.stdout.write(", ");
        }
    }
    console.log("]");
}

let s = "ABC";

// Get all sorted unique permutations
let result = findAllPermutation(s);

// Print the result
printArray(result);

Output
["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]

[Approach 3] Using Optimized Next Permutation Approach – O(n*n!) Time and O(1) Space

The idea is to optimize the previous approach by reversing the subarray after the ‘first character’ instead of sorting it, since this subarray is always in non-increasing order after the swap.

C++
// C++ Code to print all permutations in lexicographical
// order using Next Permutation Approach
#include <bits/stdc++.h>
using namespace std;

// Function to reverse substring from index 'start' to 'end'
void reverseString(string &s, int start, int end) {
    while (start < end) {
        swap(s[start], s[end]);
        start++;
        end--;
    }
}

// Function to compute the next lexicographical
// permutation of the string
bool nextPermutation(string &s) {

    int n = s.size();

    // Find the rightmost character which is
    // smaller than its next character
    int i = n - 2;
    while (i >= 0 && s[i] >= s[i + 1]) {
        i--;
    }

    // If no such character found, all permutations done
    if (i < 0) {
        return false;
    }

    // Find the ceiling of s[i]
    int j = n - 1;
    while (j > i && s[j] <= s[i]) {
        j--;
    }

    // Swap the found characters
    swap(s[i], s[j]);

    // Reverse the substring after index i
    reverseString(s, i + 1, n - 1);

    return true;
}

// Function to find all permutations using next permutation
vector<string> findAllPermutation(string s) {

    // Sort the string to start from smallest
    sort(s.begin(), s.end());

    vector<string> result;

    // Insert the first permutation
    result.push_back(s);

    // Generate all higher permutations
    while (nextPermutation(s)) {
        result.push_back(s);
    }

    return result;
}

void printArray(vector<string> &result) {
    cout << "[";
    for (int i = 0; i < result.size(); i++) {
        cout << "\"" << result[i] << "\"";
        if (i != result.size() - 1) {
            cout << ", ";
        }
    }
    cout << "]" << endl;
}

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

    // Get all sorted unique permutations
    vector<string> result = findAllPermutation(s);

    // Print the result
    printArray(result);

    return 0;
}
Java
// Java Code to print all permutations in lexicographical
// order using Next Permutation Approach
import java.util.*;

class GfG {

    // Function to reverse substring from index 'start' to 'end'
    static void reverseString(char[] s, int start, int end) {
        while (start < end) {
            char temp = s[start];
            s[start] = s[end];
            s[end] = temp;
            start++;
            end--;
        }
    }

    // Function to compute the next lexicographical
    // permutation of the string
    static boolean nextPermutation(char[] s) {

        int n = s.length;

        // Find the rightmost character which is
        // smaller than its next character
        int i = n - 2;
        while (i >= 0 && s[i] >= s[i + 1]) {
            i--;
        }

        // If no such character found, all permutations done
        if (i < 0) {
            return false;
        }

        // Find the ceiling of s[i]
        int j = n - 1;
        while (j > i && s[j] <= s[i]) {
            j--;
        }

        // Swap the found characters
        char temp = s[i];
        s[i] = s[j];
        s[j] = temp;

        // Reverse the substring after index i
        reverseString(s, i + 1, n - 1);

        return true;
    }

    // Function to find all permutations using next permutation
    static String[] findAllPermutation(String str) {

        char[] s = str.toCharArray();
        Arrays.sort(s);

        ArrayList<String> result = new ArrayList<>();

        // Insert the first permutation
        result.add(new String(s));

        // Generate all higher permutations
        while (nextPermutation(s)) {
            result.add(new String(s));
        }

        return result.toArray(new String[0]);
    }

    static void printArray(String[] result) {
        System.out.print("[");
        for (int i = 0; i < result.length; i++) {
            System.out.print("\"" + result[i] + "\"");
            if (i != result.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }

    public static void main(String[] args) {

        String s = "ABC";

        // Get all sorted unique permutations
        String[] result = findAllPermutation(s);

        // Print the result
        printArray(result);
    }
}
Python
# Python Code to print all permutations in lexicographical
# order using Next Permutation Approach

# Function to reverse substring from index 'start' to 'end'
def reverseString(s, start, end):
    while start < end:
        s[start], s[end] = s[end], s[start]
        start += 1
        end -= 1

# Function to compute the next lexicographical
# permutation of the string
def nextPermutation(s):

    n = len(s)

    # Find the rightmost character which is
    # smaller than its next character
    i = n - 2
    while i >= 0 and s[i] >= s[i + 1]:
        i -= 1

    # If no such character found, all permutations done
    if i < 0:
        return False

    # Find the ceiling of s[i]
    j = n - 1
    while j > i and s[j] <= s[i]:
        j -= 1

    # Swap the found characters
    s[i], s[j] = s[j], s[i]

    # Reverse the substring after index i
    reverseString(s, i + 1, n - 1)

    return True

# Function to find all permutations using next permutation
def findAllPermutation(str):
    s = list(str)
    s.sort()

    result = []

    # Insert the first permutation
    result.append("".join(s))

    # Generate all higher permutations
    while nextPermutation(s):
        result.append("".join(s))

    return result

def printArray(result):
    print("[", end="")
    for i in range(len(result)):
        print(f"\"{result[i]}\"", end="")
        if i != len(result) - 1:
            print(", ", end="")
    print("]")

if __name__ == "__main__":
    s = "ABC"

    # Get all sorted unique permutations
    result = findAllPermutation(s)

    # Print the result
    printArray(result)
C#
// C# Code to print all permutations in lexicographical
// order using Next Permutation Approach
using System;
using System.Collections.Generic;

class GfG {

    // Function to reverse substring from index 'start' to 'end'
    static void reverseString(char[] s, int start, int end) {
        while (start < end) {
            char temp = s[start];
            s[start] = s[end];
            s[end] = temp;
            start++;
            end--;
        }
    }

    // Function to compute the next lexicographical
    // permutation of the string
    static bool nextPermutation(char[] s) {

        int n = s.Length;

        // Find the rightmost character which is
        // smaller than its next character
        int i = n - 2;
        while (i >= 0 && s[i] >= s[i + 1]) {
            i--;
        }

        // If no such character found, all permutations done
        if (i < 0) {
            return false;
        }

        // Find the ceiling of s[i]
        int j = n - 1;
        while (j > i && s[j] <= s[i]) {
            j--;
        }

        // Swap the found characters
        char temp = s[i];
        s[i] = s[j];
        s[j] = temp;

        // Reverse the substring after index i
        reverseString(s, i + 1, n - 1);

        return true;
    }

    // Function to find all permutations using next permutation
    static string[] findAllPermutation(string str) {

        char[] s = str.ToCharArray();
        Array.Sort(s);

        List<string> result = new List<string>();

        // Insert the first permutation
        result.Add(new string(s));

        // Generate all higher permutations
        while (nextPermutation(s)) {
            result.Add(new string(s));
        }

        return result.ToArray();
    }

    static void printArray(string[] result) {
        Console.Write("[");
        for (int i = 0; i < result.Length; i++) {
            Console.Write("\"" + result[i] + "\"");
            if (i != result.Length - 1) {
                Console.Write(", ");
            }
        }
        Console.WriteLine("]");
    }

    static void Main() {

        string s = "ABC";

        // Get all sorted unique permutations
        string[] result = findAllPermutation(s);

        // Print the result
        printArray(result);
    }
}
JavaScript
// JavaScript Code to print all permutations in lexicographical
// order using Next Permutation Approach

// Function to reverse substring from index 'start' to 'end'
function reverseString(s, start, end) {
    while (start < end) {
        let temp = s[start];
        s[start] = s[end];
        s[end] = temp;
        start++;
        end--;
    }
}

// Function to compute the next lexicographical
// permutation of the string
function nextPermutation(s) {

    let n = s.length;

    // Find the rightmost character which is
    // smaller than its next character
    let i = n - 2;
    while (i >= 0 && s[i] >= s[i + 1]) {
        i--;
    }

    // If no such character found, all permutations done
    if (i < 0) {
        return false;
    }

    // Find the ceiling of s[i]
    let j = n - 1;
    while (j > i && s[j] <= s[i]) {
        j--;
    }

    // Swap the found characters
    let temp = s[i];
    s[i] = s[j];
    s[j] = temp;

    // Reverse the substring after index i
    reverseString(s, i + 1, n - 1);

    return true;
}

// Function to find all permutations using next permutation
function findAllPermutation(str) {

    let s = str.split('');
    s.sort();

    let result = [];

    // Insert the first permutation
    result.push(s.join(''));

    // Generate all higher permutations
    while (nextPermutation(s)) {
        result.push(s.join(''));
    }

    return result;
}

function printArray(result) {
    let output = "[";
    for (let i = 0; i < result.length; i++) {
        output += `"${result[i]}"`;
        if (i !== result.length - 1) {
            output += ", ";
        }
    }
    output += "]";
    console.log(output);
}

let s = "ABC";

// Get all sorted unique permutations
let result = findAllPermutation(s);

// Print the result
printArray(result);

Output
["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]


 



Next Article

Similar Reads