v9.1.1
Menu

Permutations

mediumPRORecursion & BacktrackingMeta DSA

Given an array of distinct integers, return all possible permutations.

Output each permutation on a line, space-separated, sorted lexicographically.

Example

Input
1,2,3
Output
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Reasoning
  • The algorithm starts by selecting the first element from the input array, which can be either 1, 2, or 3, resulting in three initial permutations: 1, 2, 3.
  • Then, for each initial permutation, the algorithm generates additional permutations by swapping the remaining elements, i.e., for the initial permutation 1, the algorithm swaps 2 and 3, resulting in 1 3 2.
  • The algorithm continues this process, recursively generating all possible permutations of the input array, resulting in a total of 3!=63! = 6 permutations.
  • Finally, the permutations are sorted lexicographically, resulting in the output: 1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1.

Constraints

  • 1 <= len(nums) <= 6
  • -10 <= nums[i] <= 10
  • All integers are unique

Learn this in

More from Meta DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.