AAlgoLoopSpaced repetition for LeetCode
MEDIUMBacktrackingLeetCode ↗

Permutations II

The key idea

Sort the numbers first so equal values sit next to each other. Then, at each position, skip a value if it equals its left neighbor AND that left neighbor has not been used in the current path — that one rule prunes every duplicate permutation without ever building one.

Problem

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

A permutation is an arrangement of all the elements of nums. Because nums may contain repeated values, naively generating every arrangement would yield duplicate permutations; you must return each distinct arrangement exactly once.

Constraints

Examples

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

Complexity

Time: O(n * n!) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Backtracking problems