Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,932 questions

51,869 answers

573 users

How to generate all possible permutations of an array using recursion in JavaScript

1 Answer

0 votes
/**
 * Generate all permutations of an array using recursion and backtracking
*/
function getPermutations(arr) {
    const results = [];

    // Recursive function
    function backtrack(startIndex) {
        // if we've reached the end, store a copy of the array
        if (startIndex === arr.length) {
            results.push([...arr]); 
            return;
        }

        for (let i = startIndex; i < arr.length; i++) {
            // Swap current index with the loop index
            [arr[startIndex], arr[i]] = [arr[i], arr[startIndex]];

            // Recurse for the next index
            backtrack(startIndex + 1);

            // Backtrack: swap back to restore original state
            [arr[startIndex], arr[i]] = [arr[i], arr[startIndex]];
        }
    }

    // Start recursion from index 0
    backtrack(0);
    
    return results;
}

try {
    const arr = [1, 2, 3];
    const permutations = getPermutations(arr);

    console.log("All permutations:");
    permutations.forEach(p => console.log(p));
} catch (error) {
    console.error("Error generating permutations:", error.message);
}



/*
run:

All permutations:
[ 1, 2, 3 ]
[ 1, 3, 2 ]
[ 2, 1, 3 ]
[ 2, 3, 1 ]
[ 3, 2, 1 ]
[ 3, 1, 2 ]

*/

 



answered Nov 20, 2025 by avibootz
...