Menu
CoddyTech

Permutations

MediumBacktrackingpython iconjava iconcpp iconc iconjs icon+10

You get a list nums of different integers. Return every ordering of those values, each a list that uses every value exactly once, so n values give n! orderings. List them in lexicographic order: compare two orderings position by position and let the first difference decide. For [1, 2, 3] that puts [1, 2, 3] first and [3, 2, 1] last.

Function

permute(nums: integer-array) → integer-2d-array
numsinteger-array
the values, all different, in any order
Returnsinteger-2d-array
every ordering of the values, listed in lexicographic order

Constraints

  • 1 ≤ nums.length ≤ 6
  • -10 ≤ nums[i] ≤ 10
  • All values in nums are different.
  • nums may come in any order.

Examples

Input
nums = [3, 1, 2]
Output
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Explanation
Three values have 3! = 6 orderings. Sorted, the values are 1, 2, 3, so the orderings that start with 1 come first, and [1, 2, 3] comes before [1, 3, 2] because 2 is smaller than 3 at the second position. The order of the input does not matter.

lock icon+13 hidden tests on Submit

challenge icon

Follow-up

Given one ordering, can you produce the next one in lexicographic order in place, in O(n) time and O(1) extra space?

Reset code
def permute(nums):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [3, 1, 2]

Expected

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]