Generating all permutations of n items.Grows astronomically fast.
Example
// JavaScriptfunctionpermutations(arr){if(arr.length<=1)return[arr];const result =[];for(let i =0; i < arr.length; i++){const rest =[...arr.slice(0, i),...arr.slice(i +1)];for(const perm ofpermutations(rest)){
result.push([arr[i],...perm]);}}return result;}
# Python
def get_permutations(arr):iflen(arr)<=1:return[arr[:]]
result =[]for i inrange(len(arr)):
rest = arr[:i]+ arr[i+1:]for perm inget_permutations(rest):
result.append([arr[i]]+ perm)return result
Output
Time: O(n!) | Space: O(n!) to store all permutations
Note 10! = 3,628,800 and 20! is over 2 quintillion. If n > ~10-12, factorial algorithms won't finish in time. The traveling salesman brute force is O(n!). Interviewers accept factorial only when generating all permutations is required.
Generate all orderings of elements.Backtrack: at each position,try each unused element.Swap or use a 'used' boolean array to track which elements are placed.
Example
// JavaScriptfunctionpermute(nums){const result =[];functionbacktrack(current, remaining){if(remaining.length===0){
result.push([...current]);return;}for(let i =0; i < remaining.length; i++){
current.push(remaining[i]);backtrack(current,[...remaining.slice(0, i),...remaining.slice(i +1)]);
current.pop();// undo choice}}backtrack([], nums);return result;}
# Python
def permute(nums):
result =[]
def backtrack(current, remaining):if not remaining:
result.append(current[:])returnfor i inrange(len(remaining)):
current.append(remaining[i])backtrack(current, remaining[:i]+ remaining[i+1:])
current.pop()backtrack([], nums)return result
Note Time O(n! * n), Space O(n). The 'undo choice' step (current.pop()) is the hallmark of backtracking. For permutations with duplicates: sort first, and skip if nums[i] == nums[i-1] and nums[i-1] was not used in this branch. n! grows extremely fast - practical only for n ≤ ~10.
Frequently asked questions
How does Interview Prep handle permutations?
Interview Prep covers this with 2 copy-ready snippets on this page. The "O(n!) - Factorial Time" snippet in Interview Prep uses `Generating all permutations of n items. Grows astronomically fast.`.
Which code does the Interview Prep example use?
The "O(n!) - Factorial Time" snippet uses `Generating all permutations of n items. Grows astronomically fast.`, from the Big-O Notation section of the Interview Prep cheat sheet.
What other Interview Prep snippets are shown for "permutations"?
Besides "O(n!) - Factorial Time", this page also shows "Permutations".
Is there anything to watch out for?
Yes. For "O(n!) - Factorial Time": 10! = 3,628,800 and 20! is over 2 quintillion. If n > ~10-12, factorial algorithms won't finish in time. The traveling salesman brute force is O(n!). Interviewers accept factorial only when generating all permutations is required.