Permutations (All Arrangements)
Generate all possible permutations of array elements. Total n! permutations for n distinct elements.
Visualization
Interactive visualization for Permutations (All Arrangements)
Permutations Generation
• Time: O(n! × n)
• Backtracking algorithm
• Generates all n! permutations
Interactive visualization with step-by-step execution
Implementation
1function permute(nums: number[]): number[][] {
2 const result: number[][] = [];
3
4 const backtrack = (current: number[], remaining: number[]): void => {
5 if (remaining.length === 0) {
6 result.push([...current]);
7 return;
8 }
9
10 for (let i = 0; i < remaining.length; i++) {
11 current.push(remaining[i]);
12 const newRemaining = [...remaining.slice(0, i), ...remaining.slice(i + 1)];
13 backtrack(current, newRemaining);
14 current.pop();
15 }
16 };
17
18 backtrack([], nums);
19 return result;
20}
21
22// In-place swap approach
23function permuteSwap(nums: number[]): number[][] {
24 const result: number[][] = [];
25
26 const backtrack = (start: number): void => {
27 if (start === nums.length) {
28 result.push([...nums]);
29 return;
30 }
31
32 for (let i = start; i < nums.length; i++) {
33 [nums[start], nums[i]] = [nums[i], nums[start]];
34 backtrack(start + 1);
35 [nums[start], nums[i]] = [nums[i], nums[start]];
36 }
37 };
38
39 backtrack(0);
40 return result;
41}Deep Dive
Theoretical Foundation
Use backtracking with swap or used array. For each position, try all remaining elements. Builds solution tree with n! leaves. Can optimize with pruning for duplicate elements.
Complexity
Time
O(n!)
O(n!)
O(n!)
Space
O(n!)
Applications
Use Cases
Related Algorithms
N-Queens Problem
The N-Queens Problem asks: place N chess queens on an N×N chessboard so that no two queens threaten each other. This means no two queens can be on the same row, column, or diagonal. It's a classic constraint satisfaction problem that demonstrates backtracking, pruning, and systematic exploration of solution spaces. The problem has applications in parallel processing, resource allocation, and algorithm design education.
Sudoku Solver
Sudoku Solver uses backtracking to fill a 9×9 grid with digits 1-9, ensuring each row, column, and 3×3 box contains all digits exactly once. This classic constraint satisfaction problem demonstrates systematic exploration with constraint checking. The algorithm fills empty cells one by one, backtracking when constraints are violated, making it a perfect example of pruning in search algorithms.
Combination Sum
Find all unique combinations in array where chosen numbers sum to target. Numbers can be reused. Classic backtracking problem with pruning optimization.
Generate Valid Parentheses
Generate all combinations of n pairs of well-formed parentheses. Uses backtracking with constraint that closing parentheses never exceed opening ones.