4Sum II - Problem
You're given four integer arrays nums1, nums2, nums3, and nums4, each containing n integers. Your mission is to find how many different ways you can pick one number from each array such that their sum equals zero.
More formally, return the number of tuples (i, j, k, l) where:
0 ≤ i, j, k, l < nnums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
Example:
If nums1 = [1, 2], nums2 = [-2, -1], nums3 = [-1, 2], nums4 = [0, 2]
We can form: 1 + (-2) + (-1) + 2 = 0 and 2 + (-1) + (-1) + 0 = 0
So the answer is 2.
This problem tests your ability to optimize from a naive O(n⁴) solution to an efficient O(n²) approach using hash tables and the "meet in the middle" technique.
Input & Output
example_1.py — Basic Case
$
Input:
nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
›
Output:
2
💡 Note:
Two valid combinations: 1 + (-2) + (-1) + 2 = 0 and 2 + (-1) + (-1) + 0 = 0
example_2.py — No Solutions
$
Input:
nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
›
Output:
1
💡 Note:
Only one combination possible: 0 + 0 + 0 + 0 = 0
example_3.py — Multiple Duplicates
$
Input:
nums1 = [1,1], nums2 = [-1,-1], nums3 = [1,1], nums4 = [-1,-1]
›
Output:
16
💡 Note:
All 16 combinations sum to zero: 1 + (-1) + 1 + (-1) = 0 for every (i,j,k,l) pair
Constraints
- n == nums1.length == nums2.length == nums3.length == nums4.length
- 1 ≤ n ≤ 200
- -228 ≤ nums1[i], nums2[i], nums3[i], nums4[i] ≤ 228
- All arrays have the same length
- Large integer values require careful overflow handling
Visualization
Tap to expand
Understanding the Visualization
1
Split Problem
Divide 4-array problem into two 2-array problems: (nums1, nums2) and (nums3, nums4)
2
Build Hash Map
Calculate all sums from nums1[i] + nums2[j] and store frequencies in hash table
3
Find Complements
For each nums3[k] + nums4[l], look up -(nums3[k] + nums4[l]) in hash table
4
Count Solutions
Sum up all frequencies of found complements to get total count
Key Takeaway
🎯 Key Insight: By splitting the 4-array problem into two 2-array subproblems, we reduce the complexity from O(n⁴) to O(n²), making it efficient enough for the given constraints while using the complementary sum property.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code