Permutations
mediumNeetCode 150backtrackingarrays
Problem
Given a list of distinct integers, return every possible ordering of them. The list of permutations may be returned in any order.
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]]
All six orderings.
Constraints
- • 1 <= nums.length <= 6
- • All values are distinct
Hints(tap to reveal)
- 1. Track which elements are already used.
- 2. Append an unused element, recurse, then remove it.
Optimal approach(spoiler)
- Maintain a current arrangement and a used marker per element.
- At each level append any unused element and mark it used.
- Recurse to fill the next position.
- When the arrangement is full, record a copy, then backtrack by unmarking.
- O(n * n!) time.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor