Problem 15

Abstract / Summary

Given a list of numbers find all unique triplets that add up to zero.

Note

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

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;
    }
};
32 lines | 1000 bytes | submitted August 8, 2023 | GitHub   3% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 40% (10+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
  • Two Pointers
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 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 nums contains fewer than three elements, the outer loops simply never satisfy the condition j < nums.size(), resulting in an empty result.
  • 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 need uses 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 of int.

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 nums to 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 29 | median = 5 | μ = 5.07 | σ = 1.60

Complexity Analysis

Time: polynomial
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 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++
54 links | 34 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video '3Sum - Leetcode 15 - Python'
NeetCode 13 mins
3Sum - Leetcode 15 - Python
YouTube video '3Sum | LeetCode 15 | C++, Java, Python'
Knowledge Center 23 mins
3Sum | LeetCode 15 | C++, Java, Python
YouTube video '3sum | 3sum leetcode | three sum | three sum leetcode | leetcode 15'
Naresh Gupta 12 mins
3sum | 3sum leetcode | three sum | three sum leetcode | leetcode 15
YouTube video '3Sum - LeetCode 15 - JavaScript'
AlgoJS 8 mins
3Sum - LeetCode 15 - JavaScript
YouTube video 'DSA Phir se with Sumeet | Leetcode 15 | 3Sum'
Pepcoding 19 mins
DSA Phir se with Sumeet | Leetcode 15 | 3Sum
YouTube video 'Leetcode 15 - 3Sum (JAVA Solution Explained!)'
LC Bear 14 mins
Leetcode 15 - 3Sum (JAVA Solution Explained!)
YouTube video '3Sum | Leet code 15 | Theory explained + Python code | July day 8 code challenge'
Sai Anish Malla 15 mins
3Sum | Leet code 15 | Theory explained + Python code | July day 8 code challenge
YouTube video '3Sum Problem and Solution(LeetCode 15) | Neetcode 12 / 150 | Bharath Chandra (Telugu)'
Bharath Chandra (తెలుగు) 30 mins
3Sum Problem and Solution(LeetCode 15) | Neetcode 12 / 150 | Bharath Chandra (Telugu)
YouTube video 'LeetCode 15: 3Sum - Interview Prep Ep 20'
Fisher Coder 21 mins
LeetCode 15: 3Sum - Interview Prep Ep 20
YouTube video '3-Sum | Leetcode 15 | PYTHON POINTER SOLUTION'
Cracking FAANG 20 mins
3-Sum | Leetcode 15 | PYTHON POINTER SOLUTION
YouTube video 'Leetcode 15: 3Sum in Telugu | Bruteforce, Two Pointers | Python DSA | srkcodes'
Srk Codes 23 mins
Leetcode 15: 3Sum in Telugu | Bruteforce, Two Pointers | Python DSA | srkcodes
YouTube video '3Sum Python Solution - LeetCode #15'
Professor Oakes 8 mins
3Sum Python Solution - LeetCode #15
YouTube video '3Sum | Leetcode 15 | Live coding session 🔥🔥🔥'
Coding Decoded 5 mins
3Sum | Leetcode 15 | Live coding session 🔥🔥🔥
YouTube video 'LeetCode: 15. 3Sum (Visualized)'
Code With Zi 16 mins
LeetCode: 15. 3Sum (Visualized)
YouTube video 'Leetcode 15. 3Sum'
Algorithms Casts 13 mins
Leetcode 15. 3Sum
YouTube video 'LeetCode 15: 3Sum | C# Solution | Two-Pointer Technique |'
Code Scribbler 9 mins
LeetCode 15: 3Sum | C# Solution | Two-Pointer Technique |
YouTube video '3Sum with Multiplicity | Day 15 | LeetCode |  #goProWithBroCoders'
Bro Coders 25 mins
3Sum with Multiplicity | Day 15 | LeetCode | #goProWithBroCoders
YouTube video 'Daily Leetcode #576: Oct 28, 2021 - 15. 3Sum'
Programming Live with Larry 13 mins
Daily Leetcode #576: Oct 28, 2021 - 15. 3Sum
YouTube video '3Sum - Leetcode 15 - Brute - Better - Optimal | JavaScript Two Pointers & Duplicates Solution'
Web Coder Abhishek 8 mins
3Sum - Leetcode 15 - Brute - Better - Optimal | JavaScript Two Pointers & Duplicates Solution
YouTube video 'Daily Leetcode #99: Jul 08, 2020 - 15. 3Sum'
Programming Live with Larry 63 mins
Daily Leetcode #99: Jul 08, 2020 - 15. 3Sum
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 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