Skip to main content

Permutations - Solution & Explanation

MediumArrayBacktracking18 min readAsked at: Amazon, Microsoft, Apple +22
Practice this problem

Problem Statement

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

 

Example 1:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Example 2:

Input: nums = [0,1]
Output: [[0,1],[1,0]]

Example 3:

Input: nums = [1]
Output: [[1]]

 

Constraints:

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All the integers of nums are unique.

Approach Overview

Problem Overview: Given an array of distinct integers, return all possible permutations of the numbers. Each permutation represents a different ordering of the same elements, and the result must include every possible arrangement.

Approach 1: Backtracking (Time: O(n! * n), Space: O(n))

This problem naturally fits backtracking. You build permutations incrementally by choosing an unused element, adding it to the current path, and recursively exploring further choices. A boolean used[] array or in-place swapping ensures each element appears only once in the current permutation.

The key insight is that every position in the permutation can be filled by any unused element. For each recursive level, iterate through the array, pick an unused number, append it to the current permutation, and recurse. Once the permutation length reaches n, add a copy to the result list. Then backtrack by removing the last element and marking it unused.

This generates exactly n! permutations. Copying each permutation takes O(n), which leads to an overall time complexity of O(n! * n). The recursion depth is O(n), and auxiliary space is mainly the recursion stack and the current permutation. Backtracking is the most common interview solution and heavily relies on concepts from recursion and array traversal.

Approach 2: Iterative Permutation Generation (Time: O(n! * n), Space: O(n!))

An iterative strategy builds permutations progressively. Start with a list containing an empty permutation. For each number in the input array, insert it into every possible position of every existing permutation. If a permutation has length k, inserting the new number produces k + 1 new permutations.

Example: starting with [ ], inserting 1 gives [1]. Inserting 2 into [1] creates [2,1] and [1,2]. Continue inserting the next element into every position of each existing permutation until all numbers are processed.

This approach avoids recursion and can be easier to reason about in iterative environments. However, it repeatedly copies arrays when inserting elements, which increases memory overhead. The total number of generated permutations is still n!, and each insertion operation costs up to O(n), resulting in O(n! * n) time complexity.

Recommended for interviews: Backtracking is the expected approach. It demonstrates control over recursion, state management, and pruning. Interviewers usually want to see the recursive exploration pattern and proper backtracking logic. The iterative insertion approach is useful as an alternative but appears less frequently in coding interviews.

Approach 1: Backtracking Approach

This approach uses recursion combined with backtracking to generate all possible permutations of the input array. The algorithm works by swapping elements of the array and recursively building permutations by fixing one element at a time until the entire array is permutated.

This solution provides a C implementation using the backtracking approach. The backtrack function swaps elements to fix positions and calls itself recursively to generate permutations. Whenever a complete permutation is reached (start == numsSize), it is added to the result list. Swapping is undone as part of backtracking when going back up the call stack.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n * n!) as there are n! permutations and we copy each permutation.
Space Complexity: O(n!) for storing the permutations, plus additional space used by the recursive stack.

Try this approach in the editor →

Approach 2: Iterative Permutation Generation

An alternative iterative approach utilizes a queue to generate permutations level by level by inserting each number at every possible position within every possible permutation.

This C implementation illustrates an iterative method for generating permutations using a next permutation generator. Each permutation is based on modifying and reversing array segments to derive the next permutation sequence, iteratively processed.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n * n!), iterating through permutations.
Space Complexity: O(n!) for storing permutations, constant space for current permutation array.

Try this approach in the editor →

Approach 3: DFS (Backtracking)

We design a function dfs(i) to represent that the first i positions have been filled, and now we need to fill the i+1 position. We enumerate all possible numbers, if this number has not been filled, we fill in this number, and then continue to fill the next position, until all positions are filled.

The time complexity is O(n times n!), where n is the length of the array. There are n! permutations in total, and each permutation takes O(n) time to construct.

Similar problems:

Code

Python

Java

C++

Go

TypeScript

Rust

JavaScript

C#

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Backtracking Approach

Time Complexity: O(n * n!) as there are n! permutations and we copy each permutation.
Space Complexity: O(n!) for storing the permutations, plus additional space used by the recursive stack.

Iterative Permutation Generation

Time Complexity: O(n * n!), iterating through permutations.
Space Complexity: O(n!) for storing permutations, constant space for current permutation array.

DFS (Backtracking)—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
BacktrackingO(n! * n)O(n)Standard interview approach for generating permutations using recursion
Iterative Permutation GenerationO(n! * n)O(n!)When recursion is avoided or when building permutations iteratively

Video Solution

Backtracking: Permutations - Leetcode 46 - Python • NeetCode • 422,936 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Permutations easy or hard?
Permutations is considered a medium difficulty problem. The implementation requires understanding recursion and backtracking, but the core idea is straightforward once you visualize choosing elements and undoing choices after each recursive call.
Permutations Python/Java solution
Python and Java solutions typically implement recursive backtracking. A list stores the current permutation, a boolean array tracks used numbers, and when the permutation length reaches n it gets copied into the result list.
How to solve Permutations in O(n)?
Generating every permutation cannot be done in O(n) because the output itself contains n! permutations. The optimal approach is O(n! * n) using backtracking or iterative insertion. The factorial growth comes from the number of possible arrangements.
What is the best approach for Permutations?
Backtracking is the most common and interview-preferred approach. It builds permutations step by step, recursively selecting unused elements and backtracking after exploring each branch. This guarantees all n! permutations are generated with O(n! * n) time complexity.
Is Permutations asked at Google/Amazon/Meta?
Permutation generation problems frequently appear in interviews at companies like Amazon, Google, and Meta. They test recursion, backtracking, and the ability to explore combinatorial search spaces efficiently.
What data structure is used in Permutations?
Most solutions use arrays or lists to store the current permutation and a boolean array or set to track used elements. Recursive backtracking relies on the call stack to explore choices and revert state after each branch.
What is the time complexity of Permutations?
Generating all permutations requires O(n! * n) time. There are n! possible permutations of n elements, and copying each permutation into the result list costs O(n). Any algorithm that lists all permutations will have at least factorial complexity.

Ready to solve this problem?

Practice Permutations with our built-in code editor and test cases.

Practice on FleetCode