4Sum II — LeetCode 454 Python Solution

MediumArrayHash Table
Problem
#454
Pattern
Hash Map
Reading time
2 min

The problem

Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: 0 <= i, j, k, l < n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

This statement is abridged. Read the full problem on LeetCode.

Example

Input
nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
Output
2
Explanation
The two tuples are:

Python solution

Python
class Solution:
    def fourSumCount(
        self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]
    ) -> int:
        cnt = Counter(a + b for a in nums1 for b in nums2)
        return sum(cnt[-(c + d)] for c in nums3 for d in nums4)

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n^2), where n is the length of the array auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 454. 4Sum II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 454. 4Sum II?
LeetCode 454. 4Sum II is rated Medium on LeetCode.
What is the time complexity of LeetCode 454. 4Sum II?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 454. 4Sum II?
The Python solution on this page uses O(n^2), where n is the length of the array auxiliary space.
What topics does LeetCode 454. 4Sum II cover?
LeetCode 454. 4Sum II is tagged Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview