Permutations - Problem
Generate All Permutations
Given an array
For example, if you have the numbers
Goal: Return all permutations in any order - the sequence doesn't matter as long as you include every possible arrangement.
Note: Since all integers are distinct, you don't need to worry about duplicate permutations.
Given an array
nums containing distinct integers, your task is to generate and return all possible permutations of these numbers. Think of it as finding every possible way to arrange the given numbers.For example, if you have the numbers
[1, 2, 3], you need to find all ways to arrange them: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].Goal: Return all permutations in any order - the sequence doesn't matter as long as you include every possible arrangement.
Note: Since all integers are distinct, you don't need to worry about duplicate permutations.
Input & Output
example_1.py — Basic case
$
Input:
[1,2,3]
›
Output:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
💡 Note:
For three distinct numbers, there are 3! = 6 possible arrangements. Each number appears in each position exactly twice across all permutations.
example_2.py — Two elements
$
Input:
[0,1]
›
Output:
[[0,1],[1,0]]
💡 Note:
With two elements, there are only 2! = 2 possible permutations: the original order and the reversed order.
example_3.py — Single element
$
Input:
[1]
›
Output:
[[1]]
💡 Note:
A single element has only one permutation - itself. This is our base case where 1! = 1.
Visualization
Tap to expand
Understanding the Visualization
1
Start Empty
Begin with empty arrangement []
2
Choose First
Try each number in first position: [1], [2], [3]
3
Fill Remaining
For each first choice, recursively fill remaining positions
4
Backtrack
When complete, backtrack and try next option
5
Collect Results
Gather all complete permutations
Key Takeaway
🎯 Key Insight: Backtracking systematically explores all possibilities by making choices, exploring consequences, then undoing choices to try alternatives. This guarantees we find all permutations without missing any or generating duplicates.
Time & Space Complexity
Time Complexity
O(n^n)
n nested loops, each running n times, generating n^n combinations (most invalid)
✓ Linear Growth
Space Complexity
O(n!)
Space to store all n! valid permutations in the result
⚠ Quadratic Space
Constraints
- 1 ≤ nums.length ≤ 6
- -10 ≤ nums[i] ≤ 10
- All integers in nums are distinct
- Maximum of 6! = 720 permutations possible
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code