Permutations
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Backtracking.
Permutations
Exploration vs. Selection
In permutation problems, the goal is to arrange all elements of a set in every possible order. Unlike combinations, the order matters here (
[1, 2] is different from [2, 1]).Key Backtracking Strategies
- Visited Array: Maintain a boolean array to track which elements are already included in the current permutation. This is intuitive but uses extra space.
- Swap-Based: Swap the current element with every element to its right, recurse, and then swap back. This is highly efficient as it uses the input array for state.
Given an array
nums of distinct integers, return all possible permutations. Includes visual state-space tree.Examples
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Approach 1
Level I: Backtracking with Visited Array
Intuition
Maintain a list of 'remaining' elements or a boolean array to track usage.
Iterate through all numbers. If a number is not visited, add it to the current permutation, mark it visited, and recurse. Unmark and remove after recursion.
⏱ O(N * N!)💾 O(N) for recursion stack and visited array.
Detailed Dry Run
Dry Run: nums=[1,2]
| Path | Visited | Action |
| :--- | :--- | :--- |
| [] | {F, F} | Start |
| [1] | {T, F} | Choose 1 |
| [1,2] | {T, T} | Choose 2 (Result!) |
| [1] | {T, F} | Backtrack |
| [] | {F, F} | Backtrack |
| [2] | {F, T} | Choose 2 |
| [2,1] | {T, T} | Choose 1 (Result!) |Approach 2
Level II: Backtracking with Swapping (In-Place)
Intuition
Instead of a visited array, we can rearrange the input array itself to represent the current state.
At index
first, swap nums[first] with every element from first to N-1. Recurse for first + 1. This 'fixes' one element and permutes the rest.⏱ O(N * N!)💾 O(N) for recursion stack.
Detailed Dry Run
nums=[1,2,3], first=0
- Swap(0,0): nums=[1,2,3]. Recurse first=1. 2. Swap(1,1): nums=[1,2,3]. Recurse first=2. SUCCESS [1,2,3]. 3. Swap(1,2): nums=[1,3,2]. Recurse first=2. SUCCESS [1,3,2].
- Swap(0,1): nums=[2,1,3]. Recurse first=1...
Approach 3
Level III: Iterative Lexicographical Order
Intuition
Generate permutations in lexicographical order. This is useful when the input is sorted or we need to find the 'next' permutation.
Start with the smallest permutation (sorted). Repeatedly find the next lexicographical permutation until we return to the start.
⏱ O(N * N!)💾 O(1) extra space.
Detailed Dry Run
nums=[1,2,3]
- Initial: [1,2,3]
- Next: [1,3,2]
- Next: [2,1,3]
- Next: [2,3,1]
- Next: [3,1,2]
- Next: [3,2,1]
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.