Permutations (Backtracking)
Backtracking / State ManagementO(n · n!)Solved Nov 11, 2025
Asked at 12 companies
7 recent
- Workday
- Amazon
- Microsoft
- Infosys
- Bloomberg
- Meta
- Arista Networks
- Booking.com
- Microstrategy
+2 moreShow fewer
- Zomato
- Qualcomm
Community-reported · source · updated 2026-11-18. ● asked in the last 6 months.
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 130 pointsSolved (Medium) 0/40Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Builds on: Building a new string or array as the answer · Replacing recursion with your own stack · Recursion and the call stack · The base case: where the calls stop · Depth-first traversal: preorder, inorder, postorder · Binary numbers and AND, OR, XOR
Step 2
Try it on paper
5–10 minutes, no code yet
In the wild · Sudoku solvers and regex: Try a choice, go deeper, and undo it when it fails. Solvers fill puzzles this way, and many regex engines match patterns the same way.
ProblemProblem statementGiven an array nums of distinct integers, return all the possible permutations.ReadHide
Problem Description
Given an array nums of distinct integers, return all the possible permutations.
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Use a recursive function. At each step, iterate through the elements not yet included in the current permutation. This requires tracking the state of which numbers are used.
Approaches
1. Backtracking with Swap/Visited Array (Optimal) - O(N · N!) ⭐
Idea: The total number of permutations is N!. Since copying the result takes O(N), the complexity is fixed. Permutations require managing which elements are available at the current depth of recursion.
- State Tracking: Use a boolean array (or hash set) to mark elements as
visited. - Define a recursive function
backtrack(current_permutation). - Base Case: If
current_permutationis full (sizeN), add it to results. - Recursive Step: Iterate through the entire input array. If an element
nums[i]is notvisited:- Action: Mark
nums[i]as visited, add it to thecurrent_permutation. - Recurse: Call
backtrack(...). - Backtrack: Unmark
nums[i]as visited (remove fromcurrent_permutation).
- Action: Mark
Solution code
import sys
from typing import List
class Solution:
# Optimized: O(N * N!) Time, O(N * N!) Space - Backtracking with State Tracking (Visited Array)
def permutations_optimal(self, nums: List[int]) -> List[List[int]]:
results = []
N = len(nums)
# Use a boolean array to track which elements are used (O(N) space)
visited = [False] * N
def backtrack(current_permutation):
# Base Case: Permutation is complete
if len(current_permutation) == N:
results.append(list(current_permutation))
return
for i in range(N):
if not visited[i]:
# 1. Choose: Mark as visited and add to current
visited[i] = True
current_permutation.append(nums[i])
# 2. Recurse
backtrack(current_permutation)
# 3. Backtrack: Reset state
current_permutation.pop()
visited[i] = False
backtrack([])
return results
# Brute Force: O(N * N!) - The problem is inherently factorial, so the complexity is fixed.
def permutations_brute(self, nums: List[int]) -> List[List[int]]:
return self.permutations_optimal(nums)Other ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
- Community solutions on LeetCode ↗ for many more versions, in many languages. Read them after you've solved it.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language