Welcome to Day 29 of the Tekraze DSA series. We are staying in the recursion and backtracking chapter with Permutations, which is LeetCode 46. The interesting part of this problem is not getting an answer. It is that there are two well known ways to build every arrangement, and they behave quite differently once you look closely.
One way keeps a separate path list and a used array that remembers which numbers are already taken. The other way never builds a separate path at all. It swaps numbers into place inside the input array. This post puts the two side by side so you can see what each one costs, where each one shines, and which one to reach for in an interview.
What is the Permutations problem?
You get an array nums of distinct integers. Return every possible ordering of those numbers. The answer can be in any order. LeetCode keeps the array length between 1 and 6, so the largest input has 720 permutations.
Input: nums = [1, 2, 3]
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Input: nums = [0, 1]
Output: [[0, 1], [1, 0]]
Input: nums = [1]
Output: [[1]]
An array of n distinct numbers has n factorial permutations. You have n choices for the first slot, n minus 1 for the second, and so on down to 1. Three numbers give 6 orderings and six numbers give 720.
Why are there two ways to build a permutation?
Every permutation is a series of slot filling decisions. Which number goes first, which goes second, and so on. The only real question is how you remember which numbers are still free at each step.
The used array way keeps the input untouched. It grows a separate path and marks a boolean flag for every number already placed, so the loop can skip it.
The swap way splits the input array itself into two parts. Everything before index first is already fixed, and everything from first onward is still free. Picking a number just means swapping it into position first.
Both follow the same choose, explore and undo rhythm you saw with Subsets. What changes is what you choose with and what you have to undo.
How does the used array approach work?
Start with an empty path and a boolean array full of false. At each level, loop over every index. If used[i] is true, skip it. Otherwise mark it, add nums[i] to the path, recurse, then pop the number and clear the flag. When the path length equals n, you have a full permutation, so you save a copy.
For [1, 2, 3] the first level tries 1, then 2, then 3. Under 1, the second level skips 1 because it is flagged and tries 2 and then 3. That gives [1, 2, 3] and [1, 3, 2]. Because the loop always scans from index 0, the output comes out in the same order as the input, which here is neat lexicographic order.
How does the in place swap approach work?
Here the recursive function takes one number, first, the slot you are filling now. Loop i from first to the end. Swap nums[first] with nums[i], recurse on first + 1, then swap the same pair back. When first reaches n, the whole array is one permutation, so you copy it into the result.
For [1, 2, 3] the order you get is [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1] and [3, 1, 2]. Look at the last two. Swapping 1 and 3 at the top level leaves [3, 2, 1], so 2 comes before 1 in that branch. The set of answers is identical, but the order is not sorted.
LeetCode accepts any order, so this is fine, just good to know before you compare outputs by eye.
Which one should you pick and why?
Both approaches do the same amount of work in Big O terms. The differences are practical.
Extra memory. The used array way keeps a path of size n and a flag array of size n on top of the recursion stack. The swap way needs only the recursion stack, because the input array doubles as the path.
Input safety. The swap way changes the caller’s array while it runs. It puts everything back at the end, but if you cannot touch the input, or other code reads it at the same time, copy it first. The used array way never writes to nums.
Output order. The used array way follows the input order, so a sorted input gives sorted permutations. The swap way does not.
Loop cost. The used array loop scans all n indexes at every level, even the taken ones. The swap loop only walks the free part, so it does slightly less checking. It is a small constant factor, not a Big O change.
Handling duplicates. When the input can repeat numbers, which is LeetCode 47 Permutations II, the used array way extends cleanly. Sort first and skip a number when it equals the previous one and the previous one is not in use. Deduplicating with swaps needs a set at every level, which is easier to get wrong.
Explaining it. Most people find the used array version easier to talk through on a whiteboard because the path is visible. The swap version is shorter and feels clever, but you have to explain the fixed and free split clearly.
A good default in interviews is the used array version, with a sentence about the swap version as a memory saving alternative. If the follow up is Permutations II, you are already on the right track.
What is the time and space complexity?
Time is O(n times n factorial) for both. There are n factorial permutations and copying each one into the result costs n. The internal nodes of the recursion tree add up to a smaller amount than the leaves, so they do not change the bound. Space is O(n) extra, not counting the output. The used array way holds a path, a flag array and a recursion stack, all of size n. The swap way holds only the stack.
The output itself stores n factorial lists of length n. Factorial grows even faster than 2 to the power n, and our Big O helper post on time and space complexity has a chart that makes that gap easy to see. For a refresher on arrays and lists, keep the data structures cheat sheet open.
What do the Java, Python and Rust solutions look like?
Each solution below contains both methods in one class, so you can run them side by side and compare their output.
Java solution
import java.util.*;
class Solution {
// Way 1: build a path and mark used numbers in a boolean array
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, new boolean[nums.length], new ArrayList<>(), result);
return result;
}
private void backtrack(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> result) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path)); // a full arrangement, save a copy
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true; path.add(nums[i]); // choose
backtrack(nums, used, path, result); // explore
path.remove(path.size() - 1); used[i] = false; // undo
}
}
// Way 2: swap numbers into place inside the array itself
public List<List<Integer>> permuteSwap(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
swapBacktrack(nums, 0, result);
return result;
}
private void swapBacktrack(int[] nums, int first, List<List<Integer>> result) {
if (first == nums.length) {
List<Integer> perm = new ArrayList<>();
for (int x : nums) perm.add(x);
result.add(perm);
return;
}
for (int i = first; i < nums.length; i++) {
swap(nums, first, i); // put nums[i] at position first
swapBacktrack(nums, first + 1, result);
swap(nums, first, i); // swap back to undo
}
}
private void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
}
In Java, new ArrayList<>(path) is the copy that saves you from a result full of empty lists. In the swap version we build a fresh list from the array at each leaf for the same reason.
Python solution
from typing import List
class Solution:
# Way 1: build a path and mark used numbers in a list of booleans
def permute(self, nums: List[int]) -> List[List[int]]:
result, path = [], []
used = [False] * len(nums)
def backtrack() -> None:
if len(path) == len(nums):
result.append(path[:]) # a full arrangement, save a copy
return
for i in range(len(nums)):
if used[i]:
continue
used[i] = True
path.append(nums[i]) # choose
backtrack() # explore
path.pop() # undo
used[i] = False
backtrack()
return result
# Way 2: swap numbers into place inside the list itself
def permute_swap(self, nums: List[int]) -> List[List[int]]:
nums = nums[:]
result = []
def backtrack(first: int) -> None:
if first == len(nums):
result.append(nums[:])
return
for i in range(first, len(nums)):
nums[first], nums[i] = nums[i], nums[first] # choose
backtrack(first + 1) # explore
nums[first], nums[i] = nums[i], nums[first] # undo
backtrack(0)
return result
The Python swap method copies nums at the start with nums[:], so the caller’s list is never touched. The tuple swap line nums[first], nums[i] = nums[i], nums[first] does the exchange in one step.
Rust solution
Rust has a built in Vec::swap, which makes the second method very tidy. The swap version takes nums by value as mut, so it owns its own copy and the borrow checker is happy passing one &mut Vec down the recursion.
struct Solution;
impl Solution {
// Way 1: build a path and mark used numbers in a Vec<bool>
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut result = Vec::new();
let mut path = Vec::with_capacity(nums.len());
let mut used = vec![false; nums.len()];
Self::backtrack(&nums, &mut used, &mut path, &mut result);
result
}
fn backtrack(nums: &[i32], used: &mut Vec<bool>, path: &mut Vec<i32>, result: &mut Vec<Vec<i32>>) {
if path.len() == nums.len() {
result.push(path.clone()); // a full arrangement, save a copy
return;
}
for i in 0..nums.len() {
if used[i] { continue; }
used[i] = true;
path.push(nums[i]); // choose
Self::backtrack(nums, used, path, result); // explore
path.pop(); // undo
used[i] = false;
}
}
// Way 2: swap numbers into place inside the vector itself
pub fn permute_swap(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut result = Vec::new();
Self::swap_backtrack(&mut nums, 0, &mut result);
result
}
fn swap_backtrack(nums: &mut Vec<i32>, first: usize, result: &mut Vec<Vec<i32>>) {
if first == nums.len() {
result.push(nums.clone());
return;
}
for i in first..nums.len() {
nums.swap(first, i); // choose
Self::swap_backtrack(nums, first + 1, result); // explore
nums.swap(first, i); // undo
}
}
}
All three programs ran five sample cases through both methods, for ten checks per language. The cases were the LeetCode examples [1, 2, 3], [0, 1] and [1], an array with a negative number, and a six element array that must give 720 distinct permutations. Each check confirmed the count, that nothing was repeated, and that every answer used exactly the input numbers. Every check passed in Java, Python and Rust.
What goes wrong when people mix the two methods?
- Using a used array but still looping from first like the swap version. That skips valid numbers and you lose permutations.
- Swapping without swapping back. The array drifts after each branch and you get repeats and missing orderings.
- Clearing the flag before popping, or forgetting one of the two. In the used array way both the path and the flag must be undone.
- Saving nums itself at the leaf in the swap version instead of a copy. Every saved entry then points to the same array.
- Expecting sorted output from the swap version. If a test compares exact order, sort the result first or use the used array way.
Where do permutations show up in real projects?
Generating every ordering is useful anywhere order matters and the list is small. Test tools run steps in every order to find hidden dependencies. Small route planners try every visiting order for a handful of stops. Scheduling tools check every sequence of a few jobs. Puzzle solvers and game engines explore move orders. Because n factorial explodes after about ten items, real systems pair this with pruning or switch to smarter algorithms once the list grows.
Which earlier posts in the series should you read?
If you are new to the series, Day 1, Two Sum and Day 2, Best Time to Buy and Sell Stock are the place to begin. Day 3, Contains Duplicate, Day 4, Valid Anagram and Day 5, Group Anagrams cover hashing, which is another way to track used values.
Day 6, Valid Palindrome, Day 7, Two Sum II, Day 8, 3Sum and Day 9, Container With Most Water explain two pointers, and the swap method here is a close relative of the in place swaps in that chapter. Day 10, Longest Substring Without Repeating Characters, Day 11, Longest Repeating Character Replacement and Day 12, Minimum Window Substring cover sliding windows.
The stack chapter in Day 13, Valid Parentheses, Day 14, Min Stack, Day 15, Evaluate Reverse Polish Notation and Day 16, Daily Temperatures helps you picture the call stack behind every recursive call.
Day 17, Implement Queue using Stacks builds a queue from two stacks, Day 18, Reverse Linked List, Day 19, Merge Two Sorted Lists, Day 20, Linked List Cycle, Day 21, Remove Nth Node From End of List and Day 22, Reorder List make up the linked list chapter, and Day 23, Binary Search opens the binary search chapter.
Frequently asked questions
What is the Permutations problem on LeetCode?
LeetCode 46 Permutations gives you an array of distinct integers and asks for every possible ordering of them. The answer can be returned in any order.
How many permutations does an array of n elements have?
An array of n distinct elements has n factorial permutations. Three elements give 6 orderings and six elements give 720.
What is the difference between the used array and swap methods?
The used array method builds a separate path and marks which numbers are taken, leaving the input alone. The swap method fixes numbers in place by swapping them into the current slot, which saves memory but changes the input while it runs and gives a different output order.
What is the time complexity of generating all permutations?
Both methods run in O(n times n factorial) time, because there are n factorial permutations and copying each costs n. Extra space is O(n) for the recursion stack, plus the path and flags in the used array method.
How do you handle duplicate numbers in permutations?
That is LeetCode 47 Permutations II. Sort the input, use the used array method, and skip a number when it equals the previous number and the previous one is not currently in use. This stops the same ordering from being built twice.





