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;
}
};
Difficulty
and has an acceptance rate of about 64% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Sorting
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 46: Permutations
- problem 267: Palindrome Permutation II
- problem 996: Number of Squareful Arrays
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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