4Sum II
Difficulty: Medium · Pattern: Hashing · LeetCode #454
Given four integer arrays of equal length n, count index tuples (i, j, k, l) with nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0.
Examples
text
nums1 = [1, 2], nums2 = [-2, -1], nums3 = [-1, 2], nums4 = [0, 2] → 2
nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] → 1Hints
- Brute force is O(n⁴). Split into two halves.
- Count every sum a + b in a hash map; then for each c + d, look up −(c + d).
Approach
Meet in the middle: build a map of counts of all a + b pairs (n² entries). Then for each c + d pair, add count[−(c + d)] to the answer. Total O(n²) time and space.
Complexity
Time: O(n²). Space: O(n²).
Python solution
from collections import Counter
def fourSumCount(nums1, nums2, nums3, nums4):
ab = Counter(a + b for a in nums1 for b in nums2)
return sum(ab[-(c + d)] for c in nums3 for d in nums4)JavaScript solution
function fourSumCount(nums1, nums2, nums3, nums4) {
const ab = new Map();
for (const a of nums1) for (const b of nums2) ab.set(a + b, (ab.get(a + b) || 0) + 1);
let count = 0;
for (const c of nums3) for (const d of nums4) count += ab.get(-(c + d)) || 0;
return count;
}