Permutations solution explained

To list every permutation of distinct numbers, backtrack: at each position try every value not used yet, mark it used, recurse to the next position, then unmark it. A complete arrangement is recorded when its length equals the input's. There are n! permutations and each takes O(n) to copy, so any method costs O(n × n!) time; swapping values in place is a common alternative that avoids the used array.

By Published 7 min read

Restating the task

Given a list of distinct integers, return every possible ordering of all of them. Each ordering uses every input value exactly once. The orderings may be returned in any sequence. For n values there are n × (n - 1) × ... × 1 = n! of them, so the input is always small in practice.

Output for [5, 8, 9] from the two methods on this page
MethodOrder produced
Used array589, 598, 859, 895, 958, 985 (lexicographic, because the input was sorted)
In-place swaps589, 598, 859, 895, 985, 958 (the last two arrive in a different order)
Output for [5, 8, 9] from the two methods on this page. Scroll sideways on a small screen.

Both lists contain the same six orderings, 3! = 6. An empty input has exactly one permutation, the empty list, which some test harnesses check.

What the question checks

Interviewers use Permutations to see whether you can adapt the backtracking template when order matters. The jump from Subsets is small but telling: the start index has to go, and something else must stop a value from being reused. Strong candidates also explain the cost honestly. Nothing clever can beat n! outputs, so the conversation is about correctness, memory and the duplicate-value follow-up rather than speed.

Follow-ups to prepare

  • The input has repeated values; return only distinct orderings. Sort, and skip a value if it equals its left neighbour and that neighbour is not currently in use. Code below.
  • Return only the next permutation in lexicographic order, in place. Find the rightmost position where the sequence rises, swap with the smallest larger value to its right, reverse the tail. C++ ships this as std::next_permutation, and the Next Permutation walkthrough covers it step by step.
  • Return the kth permutation directly. Use the factorial number system: counting k from zero, divide it by (n - 1)! to pick the first value, and repeat on the rest.
  • Generate them lazily. Turn the recursion into a generator so the caller can stop early without storing n! lists.

Backtracking with a used array

Keep the arrangement built so far and a boolean per input position. At each level, loop over every position. Skip the ones already used; for the others, mark, append, recurse, then pop and unmark. When the arrangement is as long as the input, copy it into the result. Because the loop always starts from the beginning, every value gets a chance at every position, which is exactly what ordering requires.

def permutations(nums):
    result, current = [], []
    used = [False] * len(nums)

    def build():
        if len(current) == len(nums):
            result.append(current[:])
            return
        for i, x in enumerate(nums):
            if used[i]:
                continue
            used[i] = True
            current.append(x)
            build()
            current.pop()
            used[i] = False

    build()
    return result
Used flags instead of a start index. O(n × n!) time, O(n) extra space.

Checking membership with if x in current would also work for distinct values, but it costs O(n) per check and fails as soon as values repeat. The used array is O(1) per check and keeps working for the duplicate follow-up.

Swapping in place, in JavaScript

Another approach needs no extra arrangement list. Treat positions 0 to pos - 1 as fixed. For position pos, swap each value from pos onward into it, recurse to fix position pos + 1, and swap back before trying the next one. When pos reaches the end, the whole array is one permutation; copy it.

function permute(nums) {
  const arr = nums.slice();
  const out = [];
  function fix(pos) {
    if (pos === arr.length) {
      out.push(arr.slice());
      return;
    }
    for (let i = pos; i < arr.length; i++) {
      [arr[pos], arr[i]] = [arr[i], arr[pos]];   // bring arr[i] to the front
      fix(pos + 1);
      [arr[pos], arr[i]] = [arr[i], arr[pos]];   // undo before the next choice
    }
  }
  fix(0);
  return out;
}
Fix one position at a time by swapping; undo each swap after the recursive call.

The output order is not lexicographic, as the table shows, because swaps shuffle the tail. If the interviewer asks for sorted output, use the used-array version on sorted input or sort the result. Forgetting the second swap is the classic bug here: the array drifts and some orderings come out twice while others never appear.

Repeated values

For [1, 4, 1], the plain method produces six lists, but only three are different: [1, 1, 4], [1, 4, 1] and [4, 1, 1]. Sort the input so equal values sit next to each other. Then, when choosing the next value, skip index i if nums[i] equals nums[i - 1] and index i - 1 is not in use. That forces equal values to be placed in their original left-to-right order, so each distinct arrangement is built exactly once.

def unique_permutations(nums):
    nums = sorted(nums)
    result, current = [], []
    used = [False] * len(nums)

    def build():
        if len(current) == len(nums):
            result.append(current[:])
            return
        for i in range(len(nums)):
            if used[i]:
                continue
            # Among equal values, only the leftmost unused copy may go next
            if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
                continue
            used[i] = True
            current.append(nums[i])
            build()
            current.pop()
            used[i] = False

    build()
    return result
Distinct permutations of a list with repeats.

Collecting into a set instead also gives the right answer, but it still generates every repeated list first, which can be far more work than the answer needs.

Time and space

n input values
MethodTimeExtra space besides the outputOutput order
Used arrayO(n × n!)O(n)Lexicographic if the input is sorted
In-place swapsO(n × n!)O(n) recursionNot sorted
Next-permutation loopO(n × n!)O(1)Lexicographic, starting from sorted input
n input values. Scroll sideways on a small screen.

Edge cases

  • Empty input: one empty permutation.
  • One value: one permutation containing it.
  • Negative numbers, which change nothing.
  • Repeated values, but only if the follow-up allows them.
  • Inputs past about ten values: 10! is already 3,628,800 lists, so ask about the real size limit.

Where it goes wrong

  • Carrying over the start index from Subsets, which only produces one ordering of each set.
  • Forgetting to unmark used[i] after the recursive call returns.
  • Not swapping back in the in-place version.
  • Storing the working list instead of a copy.
  • In the duplicate version, writing used[i - 1] instead of not used[i - 1]. Both happen to produce correct sets, but the first prunes much later and does far more work, so be ready to explain which one you wrote.

Explaining your approach

Fictional example

Contrasting permutations with subsets
Candidate
Order matters here, so I can't use a start index like in subsets. Every value has to be allowed in every position.
Candidate
I'll keep a used flag per index. At each level I try every unused value, mark it, recurse, and unmark it. When the current list is full length, I copy it out.
Candidate
There are n factorial results and each copy is n, so n times n factorial. Extra space is the recursion depth and the flags, so linear.
Interviewer
And if the input had duplicates?
Candidate
Sort first, then only let the leftmost unused copy of a value go next. That builds each distinct ordering once, without a set.

More problems like this

Subsets is the start-index version of the same template, and Combination Sum adds a target and reuse. If you want to alternate patterns, Last Stone Weight and Kth Largest Element in an Array cover heaps. Questions on recursion often come up in C++ interviews as well.

How Natively fits into practice

On Mac or Windows, Natively can read a practice problem from a screenshot, or from the page itself through its Chrome extension, and suggest the used-array or swap approach with code. Comparing that with your own attempt is a fast way to spot a missing unmark step. When you rehearse the explanation aloud, Natively transcribes it so you can tighten the wording before a real round. More on Natively for coding interviews.

Questions people ask

How do you generate all permutations of an array?

Backtrack with a used flag per element. At each position try every unused value, mark it, recurse, then unmark it, and record the arrangement when it reaches full length. Swapping values into place is an alternative.

What is the time complexity of Permutations?

O(n × n!). There are n! orderings and copying each one takes O(n). Extra space besides the output is O(n) for the recursion and the used flags.

How do you avoid duplicate permutations when values repeat?

Sort the input and skip a value when it equals the previous value and that previous copy is not in use. Equal values are then placed in a fixed order, so each distinct arrangement appears once.

Why does Permutations not use a start index like Subsets?

In Subsets the order inside a set does not matter, so a start index prevents reordered repeats. In Permutations the order is the whole point, so every unused value must be allowed at every position.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP