Skip to main content

Permutations II

Medium
Data Structures and Algorithms
Editorial
Topics:
Array
Backtracking
Recursion

Implement permuteUnique in the Solution class. The parameter nums contains integers, and a permutation is an arrangement that uses every element of nums exactly once.

Return a JSON-compatible list containing every distinct permutation of nums. If equal integer values occur multiple times, swapping those equal values does not create a new permutation, so duplicate arrangements must appear only once.

The returned permutations may be in any order. Each inner list must have the same length as nums and contain exactly the same values with the same multiplicities.

Example 1:

Input: nums = [2,2,5]
Output: [[2,2,5],[2,5,2],[5,2,2]]
Explanation: There are three arrangements because the two copies of 2 are indistinguishable.

Example 2:

Input: nums = [-1,3,0]
Output: [[-1,0,3],[-1,3,0],[0,-1,3],[0,3,-1],[3,-1,0],[3,0,-1]]
Explanation: All three values differ, so every ordering is distinct.

Example 3:

Input: nums = [4,4,4,1]
Output: [[1,4,4,4],[4,1,4,4],[4,4,1,4],[4,4,4,1]]
Explanation: The repeated 4 values produce only four distinct positions for the single 1.

Constraints:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10
  • ``nums may contain repeated integer values
  • Every returned permutation uses all elements of nums exactly once

Need help or want more practice?

Practise in an interviewGet AI Coach help