Problem 47

Abstract / Summary

Given a list of numbers that may have duplicates find all possible unique orderings of the list.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0047.cpp

class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>> result;

        sort(nums.begin(), nums.end());

        do
        {
            if (result.empty() || nums != result.back());
                result.push_back(nums);
        } while (next_permutation(nums.begin(), nums.end()));

        return result;
    }
};
16 lines | 392 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public member function permuteUnique. The function receives a mutable reference to a vector of integers and returns a vector containing all distinct permutations of the input values. The algorithm follows a deterministic approach: it first orders the input, then iterates through every lexicographically next arrangement, collecting each unique configuration into the result container.

Key Steps

Sorting the Input

sort(nums.begin(), nums.end());

Sorting places duplicate elements next to each other and establishes a canonical starting order. This preparation is essential for the subsequent generation of permutations because the standard library routine next_permutation relies on the initial ordering to produce each distinct arrangement exactly once.

Iterative Generation with next_permutation

do
{
    if (result.empty() || nums != result.back());
        result.push_back(nums);
} while (next_permutation(nums.begin(), nums.end()));

The do-while construct guarantees that the algorithm processes the initial sorted configuration before any call to next_permutation. Inside the loop, a conditional check determines whether the current permutation should be added to the output. The condition evaluates two scenarios: the result vector is still empty, or the current arrangement differs from the most recently stored permutation. When either holds true, the current nums vector is appended to result.

Returning the Collected Permutations

return result;

After the loop exhausts all possible permutations, the function returns the populated list of unique permutations to the caller.

Edge Cases Handled

When the input vector is empty, the sorting step completes without effect, and the do-while loop executes exactly once. The condition result.empty() evaluates to true, causing the empty vector to be stored as the sole permutation, which correctly reflects the mathematical definition that an empty set has one permutation-the empty sequence.

For a single-element vector, sorting leaves the element unchanged. The loop runs once, the condition again evaluates to true because result is initially empty, and the single-element vector is recorded. No further permutations exist, so the function returns a vector containing that single arrangement.

If the input contains duplicate values, sorting groups identical elements together. The next_permutation routine generates permutations in lexicographic order, automatically skipping over arrangements that would be identical after swapping equal elements. The explicit comparison nums != result.back() ensures that any repeated configuration produced by the permutation generator is not added a second time, preserving uniqueness in the final output.

Performance Optimizations Observed

The algorithm leverages the standard library’s next_permutation, which operates in place and modifies the original vector without allocating additional storage for intermediate states. This in-place transformation reduces memory overhead compared to approaches that construct new vectors for each candidate permutation.

By sorting the input once at the beginning, the code avoids repeated ordering work during the permutation process. The sorted order also enables next_permutation to generate each distinct arrangement efficiently, as it can detect when no further permutations are possible without scanning the entire vector.

The conditional check uses result.back() to compare only the most recently added permutation rather than scanning the entire result set. This localized comparison minimizes the cost of duplicate detection, especially when the number of generated permutations grows large.

Overall, the combination of a single initial sort, in-place permutation generation, and minimal duplicate checking contributes to a streamlined execution path that scales well with the size of the input while maintaining correctness for all edge conditions.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a handful of wooden blocks with numbers painted on them, and you want to lay them out in a long row to see every possible way they can be ordered. Since some of the blocks have the exact same number, you want to make sure you do not take a picture of the same arrangement twice.

First, the code lines up all the blocks from smallest to largest so it has a perfect starting point. Then, it uses a special trick to carefully swap the blocks around to create a brand new arrangement. Before it records each arrangement in a notebook, it checks the last page to see if that specific pattern is already written down. If the pattern is new and different from the last one, it adds it to the list. This step by step process continues to swap the blocks into every possible order until it has tried every single combination that exists. Once there are no more new ways to arrange the blocks, the task is finished.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.78 | σ = 2.35

Complexity Analysis

Time: factorial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong C++
martianoff Scala
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak Python
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python, Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong C++
martianoff Scala
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak Python
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
55 links | 38 authors | 10 languages

Videos

15 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality