All coding questions

Permutations

medium
NeetCode 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)
  1. Maintain a current arrangement and a used marker per element.
  2. At each level append any unused element and mark it used.
  3. Recurse to fill the next position.
  4. When the arrangement is full, record a copy, then backtrack by unmarking.
  5. 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