C++ 0015.cpp
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
map<int, int> freq;
for (auto n : nums)
freq[n]++;
// at most 3x each number
nums.clear();
for (auto f : freq)
for (auto i = 0; i < f.second && i <= 3; i++)
nums.push_back(f.first);
for (int i = 0; i < nums.size(); i++)
for (int j = i+1; j < nums.size(); j++)
{
int need = -(nums[i] + nums[j]);
auto minK = j + 1;
auto pos = lower_bound(nums.begin() + minK, nums.end(), need);
if (pos != nums.end() && *pos == need)
result.push_back({ nums[i], nums[j], need });
}
sort(result.begin(), result.end());
auto last = unique(result.begin(), result.end());
result.erase(last, result.end());
return result;
}
};
Difficulty
and has an acceptance rate of about 40% (10+ million submissions).
Typical patterns to solve this problem:
- Array
- Sorting
- Two Pointers
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 solves the classic “3-sum” problem: given an integer array, it returns all unique triplets whose sum equals zero. The algorithm proceeds in distinct phases-frequency counting, reduction of the input size, exhaustive pair enumeration with binary search, and final deduplication of results. Each phase is deliberately crafted to limit unnecessary work and to handle duplicate values gracefully.
Frequency Counting
The first phase builds a frequency map that records how many times each distinct integer appears in the original vector. This map is later used to constrain the number of copies of each value that participate in the search.
map<int, int> freq;
for (auto n : nums)
freq[n]++;
By using an ordered map, the keys are automatically sorted, which later simplifies the binary search step because the reduced nums vector inherits this order.
Limiting Duplicates
A naïve 3-sum solution would iterate over the full input, leading to many redundant checks when the same value appears many times. This implementation caps the contribution of any value to at most three occurrences, because a valid zero-sum triplet cannot require more than three copies of the same number. The loop that rebuilds nums respects this bound.
nums.clear();
for (auto f : freq)
for (auto i = 0; i < f.second && i <= 3; i++)
nums.push_back(f.first);
The inner condition i <= 3 ensures that even if a number appears thousands of times, only the first three copies are retained. This dramatically shrinks the search space while preserving all possible valid triplets.
Pair Enumeration with Binary Search
The core search iterates over all ordered pairs (i, j) where i < j. For each pair, the algorithm computes the complementary value needed to reach a sum of zero and then searches for that value in the tail of the vector using lower_bound. Because nums is sorted, lower_bound performs a binary search, locating the first position where the needed value could appear.
for (int i = 0; i < nums.size(); i++)
for (int j = i+1; j < nums.size(); j++)
{
int need = -(nums[i] + nums[j]);
auto minK = j + 1;
auto pos = lower_bound(nums.begin() + minK, nums.end(), need);
if (pos != nums.end() && *pos == need)
result.push_back({ nums[i], nums[j], need });
}
The variable minK guarantees that the third index is always strictly greater than j, preserving the required ordering of indices and preventing reuse of the same element within a single triplet. The conditional check after lower_bound confirms that the exact needed value exists; otherwise the pair is discarded.
Result Deduplication
Even with the duplicate-limiting step, different index combinations can generate identical triplets (for example, when the input contains multiple zeros). To ensure each unique combination appears only once, the algorithm sorts the list of found triplets and then removes consecutive duplicates using unique.
sort(result.begin(), result.end());
auto last = unique(result.begin(), result.end());
result.erase(last, result.end());
Sorting the triplets lexicographically puts identical ones next to each other, allowing unique to collapse them efficiently. The final erase call trims the vector to contain only the distinct results.
Edge Cases Handled
The code naturally accommodates several edge conditions:
- All zeros: The frequency map records the count of zero, and the limiting step retains up to three zeros, enabling the triplet
{0,0,0}to be discovered while preventing extraneous repetitions. - Insufficient distinct numbers: If the reduced
numscontains fewer than three elements, the outer loops simply never satisfy the conditionj < nums.size(), resulting in an emptyresult. - Large duplicate blocks: When a number appears many times (e.g., 1000 copies of
5), the cap at three copies ensures the algorithm does not waste time iterating over redundant entries. - Mixed positive and negative values: The binary search correctly finds the complementary value regardless of sign, because the vector is sorted in ascending order.
- Presence of extreme integer values: The computation of
needuses standard integer arithmetic; the algorithm does not rely on overflow-prone tricks, so it behaves correctly even when the sum of two large magnitude numbers approaches the limits ofint.
Performance Optimizations
Several deliberate choices improve runtime efficiency:
- Frequency map construction reduces the problem size before the expensive double loop, turning a potentially O(n³) scenario into a much smaller search space.
- Capping duplicates at three eliminates unnecessary iterations over identical values, which is especially beneficial for inputs with heavy repetition.
- Ordered map provides a naturally sorted key set, allowing the rebuilt
numsto be sorted without an extra sorting pass. - Binary search (
lower_bound) replaces a linear scan for the third element, cutting the inner search from linear to logarithmic time relative to the remaining suffix length. - Sorting and unique deduplication are performed only once after all candidate triplets are collected, avoiding repeated checks during the main enumeration phase.
Collectively, these optimizations ensure that the algorithm scales well for typical input sizes while maintaining correctness across a wide range of scenarios.
ELI5 - Simplified Explanation
Imagine you have a big pile of numbered blocks and you want to find three blocks that add up to exactly zero. Every time you pick three blocks, they have to be special because their numbers joined together make nothing at all.
First, the code looks at all the blocks you have and counts them up so it knows exactly what is in the pile. If there are too many of the same block, it puts some away so things do not get too crowded.
Next, it starts picking two blocks from the pile one by one. Once it has those two, it does a little bit of math to figure out what the third block should be to reach zero. It checks if that third block is hidden somewhere else in the pile. If the block is found, those three are put aside as a successful group.
Finally, because there might be some groups that are exactly the same, the code sorts through everything to make sure every group is unique and keeps only the special sets that fit the rule.
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 | C# | JS | Java | C | Rust | Ruby | Go | PHP | TS | ||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| chandansgowda | Python | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| lennylxx | C++ | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| MacJim | C++ | ||||||||||||
| qiyuangong | Java | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, PHP, Python, Ruby, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| AdelDaniel | Dart | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| chandansgowda | Python | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| lennylxx | C++ | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| MacJim | C++ | ||||||||||||
| qiyuangong | Java | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 1: Two Sum
- problem 16: 3Sum Closest
- problem 18: 4Sum
- problem 2367: Number of Arithmetic Triplets
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 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 47: Permutations II
- 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