4Sum II - 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 < nnums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
Find all combinations of indices where one element from each array sums to zero.
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [1,-1], nums2 = [-1,1], nums3 = [-1,1], nums4 = [1,-1]
›
Output:
2
💡 Note:
Two valid tuples: nums1[0]+nums2[0]+nums3[0]+nums4[0] = 1+(-1)+(-1)+1 = 0, and nums1[1]+nums2[1]+nums3[1]+nums4[1] = (-1)+1+1+(-1) = 0
Example 2 — All Zeros
$
Input:
nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
›
Output:
1
💡 Note:
Only one combination possible: 0+0+0+0 = 0
Example 3 — No Valid Combinations
$
Input:
nums1 = [1,2], nums2 = [1,2], nums3 = [1,2], nums4 = [1,2]
›
Output:
0
💡 Note:
All elements are positive, minimum sum is 1+1+1+1 = 4, cannot equal 0
Constraints
- n == nums1.length == nums2.length == nums3.length == nums4.length
- 1 ≤ n ≤ 200
- -228 ≤ nums1[i], nums2[i], nums3[i], nums4[i] ≤ 228
Visualization
Tap to expand
Understanding the Visualization
1
Input
Four arrays of equal length with integers
2
Process
Find combinations where one element from each array sums to 0
3
Output
Count of valid 4-tuples
Key Takeaway
🎯 Key Insight: Split into two pairs and use hash map to avoid O(n⁴) brute force
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code