Problem 454

Abstract / Summary

Given four integer lists, find how many quadruplets sum to zero.

Note

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

Python 0454.py

class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        size = len(nums1)

        ab = defaultdict(int)
        cd = defaultdict(int)
        for i in range(size):
            for j in range(size):
                ab[nums1[i] + nums2[j]] += 1
                cd[nums3[i] + nums4[j]] += 1

        result = 0
        for x in ab:
            if -x in cd:
                result += ab[x] * cd[-x]

        return result
17 lines | 511 bytes | submitted August 19, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (600k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
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 “4-Sum II” problem: given four integer arrays of equal length, it counts the number of quadruplets ((i, j, k, l)) such that the sum of the selected elements from each array equals zero. The algorithm builds frequency maps for all possible pairwise sums from the first two arrays and from the last two arrays, then combines these maps to compute the total count.

Core Logic

The method begins by determining the common length of the input arrays. This length is used for the nested loops that generate pairwise sums.

size = len(nums1)

Two hash tables are created with defaultdict(int). These structures automatically initialize missing keys to zero, which simplifies the counting logic.

ab = defaultdict(int)
cd = defaultdict(int)

The next section populates the two dictionaries. For every index i in the range of the array size, the inner loop iterates over every index j. The sum of nums1[i] and nums2[j] increments the corresponding entry in ab. Simultaneously, the sum of nums3[i] and nums4[j] increments the entry in cd. By iterating over both dimensions, the code captures every possible pair from each half of the input.

for i in range(size):
    for j in range(size):
        ab[nums1[i] + nums2[j]] += 1
        cd[nums3[i] + nums4[j]] += 1

After the frequency maps are ready, the algorithm iterates over the keys of ab. For each sum x, it checks whether the negated value -x exists in cd. If such a complementary sum is present, the product of the two frequencies represents the number of quadruplets that combine to zero for that particular pair of sums. The result accumulator is updated accordingly.

result = 0
for x in ab:
    if -x in cd:
        result += ab[x] * cd[-x]

Finally, the accumulated count is returned.

return result

Edge Cases Handled

The algorithm gracefully handles empty input arrays. When size is zero, the nested loops never execute, leaving both dictionaries empty. The subsequent iteration over ab also skips, resulting in a returned count of zero, which is the correct answer for an empty problem instance.

Duplicate values within any of the input arrays are naturally accommodated because the frequency maps count each occurrence of a pair sum. For example, if several different index pairs produce the same sum, the corresponding dictionary entry aggregates the total number of ways that sum can be formed, ensuring that all valid quadruplets are accounted for.

The code also works correctly with negative numbers. Since the dictionaries store sums without any assumptions about sign, a negative sum from the first two arrays will correctly match a positive counterpart from the last two arrays (or vice-versa) when the condition -x in cd is evaluated.

Large integer values are supported because Python integers have arbitrary precision. The addition operations and dictionary keys can represent any integer result without overflow concerns.

Performance Optimizations

A primary optimization is the reduction of the naïve (O(n^4)) enumeration to an (O(n^2)) approach by precomputing pairwise sums. By collapsing two dimensions into a single hash table lookup, the algorithm avoids the combinatorial explosion of iterating over all quadruplets.

Using defaultdict(int) eliminates the need for explicit existence checks before incrementing a count. This reduces the overhead of conditional logic inside the innermost loop, allowing the interpreter to perform the increment in a single statement.

The final aggregation step iterates only over the distinct sums present in the first hash table. Because many pairwise sums may collide, the number of iterations can be substantially smaller than the total number of pairs, especially when the input contains repeated values or a limited range of numbers. This selective traversal further trims the amount of work required to compute the final result.

By separating the computation of the two halves of the problem (ab and cd) and then performing a single pass to combine them, the implementation maximizes cache locality: each dictionary is built in a tight loop, and the combination loop accesses each dictionary in a read-only fashion, which is friendly to modern CPU memory hierarchies.

written by openai gpt

ELI5 - Simplified Explanation

Imagine playing with four different boxes of colorful building blocks, where each box has a handful of blocks with numbers written on them. The goal is to pick one block from each box so that when you add all four numbers together, the final answer is zero.

To solve this, first think about how many ways to pick a block from the first box and a block from the second box to get a certain sum. You store these sums in a notebook, writing down each total and how many different pairs of blocks help make it. You do the exact same thing for the third and fourth boxes, keeping track of those sums in a second notebook.

Now comes the clever part. You look through the first notebook where the sums of the first two boxes are written down. For every sum in that notebook, you check if the opposite number exists in the second notebook. For example, if you have a five in the first notebook, you check the second one to see if there is a negative five. If you find one, it means you can combine those specific pairs to reach zero. You multiply the number of ways to get five by the number of ways to get negative five, and keep a running tally of all these possibilities until you have checked everything.

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 = 8 | μ = 7.93 | σ = 0.98

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 Go Java Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github everthis JS
fpdjsns C++
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
martianoff Scala
sonugiri1043 C++
suxrobGM C#
trung-hn Python
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
everthis JavaScript
fpdjsns C++
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
martianoff Scala
sonugiri1043 C++
suxrobGM C#
trung-hn Python
YuriSpiridonov Python
zfang399 C++
35 links | 21 authors | 9 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

2 easy 6 medium 1 hard
10 solutions   August 19, 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