> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Permutations II Python Solution with Tests

> Tested Python solution for LeetCode 47 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 47, Medium. Topics: Array, Backtracking, Sorting. [View on LeetCode](https://leetcode.com/problems/permutations-ii/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 47   # by problem number
lcpy gen -s permutations_ii   # by problem name
```

## Problem

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

### 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]]
```

### Constraints

* `1 <= nums.length <= 8`
* `-10 <= nums[i] <= 10`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/permutations_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/permutations_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n * n!)
    # Space: O(n)
    def permute_unique(self, nums: list[int]) -> list[list[int]]:
        nums.sort()
        result: list[list[int]] = []
        used = [False] * len(nums)

        def backtrack(current: list[int]) -> None:
            if len(current) == len(nums):
                result.append(list(current))
                return
            for i in range(len(nums)):
                if used[i]:
                    continue
                if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
                    continue
                used[i] = True
                current.append(nums[i])
                backtrack(current)
                current.pop()
                used[i] = False

        backtrack([])
        return result
```

## Complexity

| Time       | Space |
| ---------- | ----- |
| O(n \* n!) | O(n)  |

## Tags

[NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
