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,933 questions

51,870 answers

573 users

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

1 Answer

0 votes
/**
 * Generate all permutations of an array using recursion.
 */
function generatePermutations<T>(arr: T[]): T[][] {
    // Validate input
    if (!Array.isArray(arr)) {
        throw new Error("Input must be an array.");
    }

    const results: T[][] = [];

    /**
     * Recursive function to build permutations.
     */
    function backtrack(current: T[], remaining: T[]) {
        if (remaining.length === 0) {
            results.push([...current]); // Push a copy of the current permutation
            return;
        }

        for (let i = 0; i < remaining.length; i++) {
            const next = remaining[i];
            const newRemaining = [...remaining.slice(0, i), ...remaining.slice(i + 1)];
            current.push(next);
            backtrack(current, newRemaining);
            current.pop(); // Backtrack
        }
    }

    backtrack([], arr);

    return results;
}

try {
    const input: number[] = [1, 2, 3];
    const permutations: number[][] = generatePermutations(input);

    console.log(`All permutations of [${input}]:`);
    permutations.forEach(p => console.log(p));
} catch (error) {
    console.error("Error:", (error as Error).message);
}



/*
run:

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

*/

 



answered Nov 20, 2025 by avibootz
...