Imagine you are organizing a race and want to list all possible orders in which runners can finish. How many ways can you arrange them, and how do you generate each order?
Given an array of distinct integers nums, return all possible permutations. You can return the answer in any order.
Input: An array nums of distinct integers.
Output: A list of lists, where each list is a unique permutation of nums.
1 ≤ nums.length ≤ 8All elements of nums are distinct integers
Edge cases: Empty array → [] (no permutations)Single element array → [[element]] (only one permutation)Array with two elements → two permutations swapping order
def permute(nums: list[int]) -> list[list[int]]:public List<List<Integer>> permute(int[] nums)vector<vector<int>> permute(vector<int>& nums)function permute(nums)
def permute(nums):
# Write your solution here
pass
class Solution {
public List<List<Integer>> permute(int[] nums) {
// Write your solution here
return new ArrayList<>();
}
}
#include <vector>
using namespace std;
vector<vector<int>> permute(vector<int>& nums) {
// Write your solution here
return {};
}
function permute(nums) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: [[1,2,3],[1,3,2],[2,1,3]]Greedy approach that stops recursion early or picks only first unused element.✅ In backtracking, loop over all unused elements at each recursion level instead of picking first only.
Wrong: [[1,1,1],[1,1,1],[1,1,1]]Reusing elements multiple times in the same permutation (unbounded instead of 0/1).✅ Use a used array to mark elements as used and prevent reuse in the same path.
Wrong: [[]]Returning a list with an empty permutation for empty input instead of empty list.✅ Return [] immediately if input is empty; do not add empty path as a permutation.
Wrong: [[4,5]]Not exploring all permutations for two elements; missing swapped order.✅ Ensure recursion explores all unused elements at each step.