Skip to the solution
MediumDSA9 min read

How do you generate all permutations of an array?

800 views

The problem

Question presented to candidate: "Given a list of distinct integers, return all of its permutations. Write it in Python with backtracking, and then tell me how you would handle duplicate values."

What a strong answer should cover:

  • There are n! permutations of n distinct elements: n choices for the first position, n - 1 for the second, and so on.
  • Backtracking with a used marker: pick any unused element for the next position, recurse, then undo both the path and the marker.
  • The in-place swap alternative (fix position k by swapping each candidate into it) and how its output order differs.
  • Complexity O(n ยท n!) time, O(n) extra space; impossible to beat when all permutations must be listed.
  • Duplicates (Permutations II): sort, and skip nums[i] when it equals nums[i - 1] and nums[i - 1] is not used; or the next-permutation algorithm.
  • Python details: copy with path[:], the tuple swap a[k], a[i] = a[i], a[k], and itertools.permutations as the library version โ€” which treats equal values as different, so it repeats permutations of [1, 1, 2].

Clarifying questions expected:

  • Are the values distinct, and if not, should equal permutations appear once?
  • Does the output need to be in sorted (lexicographic) order?
  • Do you need all of them, or just the next one / the k-th one?

Code / implementation expected: Yes โ€” a backtracking function in Python with a used list (or in-place swaps), plus the duplicate-skip rule.

  • dsa
  • backtracking
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonPermutations two ways (used[] and swaps), and how n! grows
PythonPermutations II with duplicates, and the next-permutation algorithm

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 65 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you get the right-side view of a binary tree?

Continue