Python 0018.py
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
# each number should occur at most four times
freq = defaultdict(int)
for n in nums:
freq[n] += 1
reduced = []
for f in freq:
count = min(4, freq[f])
for _ in range(count):
reduced.append(f)
nums = reduced
# all pairs(i, j) where i < j, grouped by their sum
two = defaultdict(set)
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
x = nums[i]
y = nums[j]
two[x + y].add(tuple([ i, j ]))
result = set()
for x in two:
y = target - x
if not y in two:
continue
if x > y: # optimization, avoid duplicates
continue
for tx in two[x]:
for ty in two[y]:
a = tx[0]
b = tx[1]
c = ty[0]
d = ty[1]
if a != c and a != d and b != c and b != d: # a<b and c<d are guaranteed
four = [ nums[a], nums[b], nums[c], nums[d] ]
four.sort()
result.add(tuple(four))
return result
Difficulty
and has an acceptance rate of about 41% (4+ 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 “4-sum” problem: given an integer array and a target value, it returns all unique quadruplets whose elements sum to the target. The algorithm proceeds in three logical phases: frequency reduction, pair-sum indexing, and combination of complementary pairs. Throughout these phases the code enforces constraints on element multiplicity, eliminates duplicate quadruplets, and ensures that indices used in a quadruplet are distinct.
Frequency Reduction
The first phase limits the number of occurrences of any value to at most four. This bound is sufficient because a valid quadruplet cannot contain more than four copies of the same number. The code builds a frequency map, then constructs a reduced list that contains each distinct value no more than four times.
freq = defaultdict(int)
for n in nums:
freq[n] += 1
reduced = []
for f in freq:
count = min(4, freq[f])
for _ in range(count):
reduced.append(f)
nums = reduced
By truncating excess repetitions early, the algorithm prevents unnecessary work in later stages while preserving every possible quadruplet.
Pair-Sum Indexing
The second phase enumerates all unordered index pairs (i, j) with i < j and groups them by the sum of their corresponding values. The grouping is stored in a dictionary where each key is a pair sum and each value is a set of index tuples that produce that sum.
two = defaultdict(set)
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
x = nums[i]
y = nums[j]
two[x + y].add(tuple([ i, j ]))
Using a set for the value collection guarantees that duplicate index pairs are not stored, even if the same numeric pair appears multiple times in the input.
Combining Complementary Pairs
The final phase iterates over each distinct pair-sum x. For each x it computes the complementary sum y = target - x. If y is present in the dictionary, the algorithm proceeds only when x is less than or equal to y. This ordering eliminates symmetric duplicate work because the pair (x, y) and (y, x) would otherwise generate the same quadruplets twice.
result = set()
for x in two:
y = target - x
if not y in two:
continue
if x > y: # optimization, avoid duplicates
continue
Within the nested loops over the index pairs belonging to x and y, the code extracts the four indices a, b, c, d. A crucial check ensures that all four indices are distinct, thereby preventing the reuse of the same element in a single quadruplet.
for tx in two[x]:
for ty in two[y]:
a = tx[0]
b = tx[1]
c = ty[0]
d = ty[1]
if a != c and a != d and b != c and b != d: # a<b and c<d are guaranteed
four = [ nums[a], nums[b], nums[c], nums[d] ]
four.sort()
result.add(tuple(four))
The quadruplet is sorted before being added to the result set, which normalizes the order of elements and enables the set to automatically discard duplicate quadruplets that differ only in ordering.
Edge Cases Handled
The algorithm gracefully handles inputs where the original array contains many duplicate values. By capping each value’s frequency at four, it still produces all valid quadruplets while discarding superfluous repetitions that could not contribute to a new solution.
When the target sum cannot be expressed as the sum of any two pair-sums, the inner loop is bypassed entirely because the complementary sum y is absent from the dictionary. This early exit avoids unnecessary combination attempts.
The distinct-index check guarantees correctness when the same numeric value appears at multiple positions. Even if two different pairs share a numeric value, they will be considered only if the underlying indices differ, thereby respecting the requirement that each array element be used at most once per quadruplet.
If the input list is empty or contains fewer than four elements after reduction, the pair-sum dictionary will have insufficient entries to satisfy the combination criteria, and the function will return an empty set, which correctly represents the absence of any quadruplet.
Performance Optimizations
The frequency-capping step reduces the effective input size, which directly limits the number of pair combinations generated in the second phase. This reduction is especially beneficial for inputs with high multiplicities of a single value.
Storing pair indices in a set prevents duplicate storage of identical index pairs, saving memory and avoiding redundant work during the combination phase.
The condition if x > y: continue eliminates symmetric processing of complementary pair-sums. By enforcing an ordering on the sums, each unordered pair of sums is examined exactly once, halving the number of combination checks in the worst case.
Using a set for the final results, together with sorting each quadruplet before insertion, ensures that duplicate quadruplets are automatically filtered without requiring an explicit duplicate-detection routine.
The nested loops over two[x] and two[y] operate only on the relevant subsets of index pairs, rather than iterating over the entire list of numbers repeatedly. This localized iteration reduces the overall number of comparisons needed to assemble candidate quadruplets.
ELI5 - Simplified Explanation
Imagine having a big box of toy bricks with numbers written on them. You want to find four bricks that add up to a specific total number you have in your head.
First, look through the whole pile. If there are too many of the same number, put some back so there are never more than four of any single number. This kept the pile smaller and easier to manage.
Next, pick every possible pair of bricks from the pile. Add their numbers together and write the pair down in a notebook under the sum they created. This notebook helps keep track of which bricks can work together to make certain amounts.
Now, look at the target number. If you have a sum in the notebook that, when added to another sum in the notebook, makes the target, then those two pairs might be the perfect group of four. Check to make sure the four bricks are all different pieces from the original pile. If they are, line them up and put them into a collection of winning groups. If you have any groups that were already found, ignore them so you do not have to write the same answer more than once.
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 | Go | PHP | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | aylei | Rust | |||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| everthis | JS | ||||||||||||
| fengvyi | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| martianoff | Scala | ||||||||||||
| qiyuangong | Python | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, PHP, Python, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fengvyi | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| martianoff | Scala | ||||||||||||
| qiyuangong | Python | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
Solved On The Same Day
- problem 205: Isomorphic Strings
- problem 905: Sort Array By Parity
- problem 922: Sort Array By Parity II
- problem 2423: Remove Letter To Equalize Frequency
- problem 80: Remove Duplicates from Sorted Array II
- problem 92: Reverse Linked List II
- problem 93: Restore IP Addresses
- problem 384: Shuffle an Array
- problem 1143: Longest Common Subsequence
- problem 1615: Maximal Network Rank
- problem 32: Longest Valid Parentheses
- problem 149: Max Points on a Line
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