16. Permutations
mediumAsked at SwiggyReturn every permutation of a distinct-integer array.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array nums of distinct integers, return all possible permutations. The order of permutations in the answer does not matter.
Constraints
1 <= nums.length <= 6All values are distinct-10 <= nums[i] <= 10
Examples
Example 1
nums=[1,2,3][[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]Example 2
nums=[0,1][[0,1],[1,0]]Approaches
1. Insert into all positions
Build by inserting each new number into every position of existing permutations.
- Time
- O(n * n!)
- Space
- O(n * n!)
let res=[[]];
for (const x of nums) {
const next=[];
for (const p of res)
for (let i=0;i<=p.length;i++)
next.push([...p.slice(0,i),x,...p.slice(i)]);
res=next;
}
return res;Tradeoff:
2. Backtracking with used set
Recurse, picking any unused index next. When the current arrangement reaches length n, copy and store it. Undo each choice before trying the next.
- Time
- O(n * n!)
- Space
- O(n)
function permute(nums) {
const res = [];
const used = Array(nums.length).fill(false);
const path = [];
const dfs = () => {
if (path.length === nums.length) { res.push([...path]); return; }
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true;
path.push(nums[i]);
dfs();
path.pop();
used[i] = false;
}
};
dfs();
return res;
}Tradeoff:
Swiggy-specific tips
Swiggy uses permutations to probe backtracking fluency — they care more about clean undo logic than micro-optimizations, because their courier-assignment search uses the same shape.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Permutations and other Swiggy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →