Skip to main content

18. Permutations

mediumAsked at Ramp

Return all possible orderings of distinct integers.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Constraints

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All integers of nums are unique

Examples

Example 1

Input
nums = [1,2,3]
Output
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Example 2

Input
nums = [0,1]
Output
[[0,1],[1,0]]

Approaches

1. Brute force with used-set

Build permutations by repeatedly scanning the input for unused elements.

Time
O(n! * n)
Space
O(n)
function permute(nums) {
  const out = [];
  function build(cur) {
    if (cur.length === nums.length) { out.push([...cur]); return; }
    for (const n of nums) if (!cur.includes(n)) { cur.push(n); build(cur); cur.pop(); }
  }
  build([]);
  return out;
}

Tradeoff:

2. Backtracking with swap-in-place

Recurse with index k; for each i >= k, swap nums[k] with nums[i], recurse on k+1, swap back. Avoids the used-array.

Time
O(n!)
Space
O(n)
function permute(nums) {
  const out = [];
  function backtrack(k) {
    if (k === nums.length) { out.push([...nums]); return; }
    for (let i = k; i < nums.length; i++) {
      [nums[k], nums[i]] = [nums[i], nums[k]];
      backtrack(k + 1);
      [nums[k], nums[i]] = [nums[i], nums[k]];
    }
  }
  backtrack(0);
  return out;
}

Tradeoff:

Ramp-specific tips

Ramp grades this on the in-place swap pattern because their AP automation enumerates approval orderings without materializing each candidate route — same shape, same memory discipline.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Permutations and other Ramp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →