Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Permutations

mediumbacktracking

Problem

Given an array nums of distinct integers, return every possible ordering of its elements. The orderings may be returned in any sequence, but each must appear exactly once.

  • Up to 8 elements.
  • Each value is between -20 and 20.
  • All values are distinct.

Examples

  • nums = [4, 5, 6] → [[4,5,6], [4,6,5], [5,4,6], [5,6,4], [6,4,5], [6,5,4]] in any order; 3! = 6 results.
  • nums = [0, 8] → [[0,8], [8,0]].
  • nums = [7] → [[7]].

Hints

  1. Fix the element that goes first. How many ways are there to arrange the rest, and does that sub-problem look like the original?
  2. Keep track of which elements are already placed so you never reuse one within the same ordering.
  3. Backtracking with a used array (or in-place swapping); record the path when its length reaches n.

Last reviewed 8 September 2026