Permutations
Medium · Backtracking
You are given an array of distinct integers. Return all possible orderings (permutations) of the array, each as its own list. Every element must appear exactly once in each ordering, and every possible arrangement must be included exactly once overall, 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]]
Why: There are 3! = 6 distinct ways to arrange three unique numbers, and all are listed.
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Why: With two elements there are only 2 possible orderings.
Input: nums = [5]
Output: [[5]]
Why: A single element has only one possible arrangement.
Constraints
1 <= nums.length <= 6, -10 <= nums[i] <= 10, all nums[i] are distinct
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Permutations. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.