Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Generate All Permutations

A Closer Look at Functionshard

Implement `permutations(arr)` that returns an array of all orderings of the input array's elements. For each position, fix one element as the first and recurse on the rest, so the orderings come out in a predictable sequence. Assume the elements are distinct.

Examples

Input: [1, 2, 3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: [1]
Output: [[1]]

Sample tests

Input: permutations([1,2,3])
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: permutations([1])
Output: [[1]]

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Mutating the input array while building `rest` corrupts later iterations — build a fresh array with `slice`/`concat`.
  • Returning the original array reference instead of a copy in the base case lets callers mutate shared state.

Learning resources

  • MDN: Recursion
Approach & explanation (try first)

The number of permutations is n!. Fixing each element as the head and recursively permuting the rest enumerates them all without duplicates (given distinct inputs). Slicing keeps each recursive call working on its own array.

Loading...
⌘/Ctrl + Enter

Run your code to see results.