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 < n
  • nums1[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: 6
💡 Note: Six valid tuples: (0,0,0,0): 1+(-1)+(-1)+1=0, (0,0,1,1): 1+(-1)+1+(-1)=0, (0,1,0,1): 1+1+(-1)+(-1)=0, (1,0,1,0): (-1)+(-1)+1+1=0, (1,1,0,0): (-1)+1+(-1)+1=0, (1,1,1,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
4Sum II Problem INPUT nums1: 1 -1 nums2: -1 1 nums3: -1 1 nums4: 1 -1 Goal: Find tuples (i,j,k,l) nums1[i]+nums2[j]+nums3[k]+nums4[l]=0 Array Length: n = 2 Total combinations: 2 x 2 x 2 x 2 = 16 Need efficient approach! ALGORITHM (Hash Map) 1 Build HashMap Store sums of nums1+nums2 map[sum] = count 1+(-1)=0, 1+1=2 (-1)+(-1)=-2, (-1)+1=0 map: {0:2, 2:1, -2:1} 2 Check nums3+nums4 Look for -(nums3+nums4) in map 3 Calculate Pairs (-1)+1=0, need 0 in map nums3[k]+nums4[l] | need | cnt -1 + 1 = 0 | 0 | 2 -1 + (-1) = -2 | 2 | 1 1 + 1 = 2 | -2 | 1 1 + (-1) = 0 | 0 | 2 4 Sum All Counts Total valid tuples found FINAL RESULT Count Calculation: 2 + 1 + 1 + 2 = 6 Wait! Only count where -(nums3+nums4) exists in map 0 exists: 2 matches 0 exists: 2 matches OUTPUT 2 Valid Tuples: (0,1,0,0): 1+1+(-1)+(-1)=0 (1,0,1,1): (-1)+(-1)+1+1=0 OK - 2 tuples found! Key Insight: Split 4 arrays into 2 groups: (nums1, nums2) and (nums3, nums4). Store all sums of first group in HashMap. For each sum in second group, check if negation exists in map. Time: O(n^2), Space: O(n^2) This reduces O(n^4) brute force to O(n^2) using the "meet in the middle" technique with hashing. TutorialsPoint - 4Sum II | Hash Map Approach
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
125.1K Views
Medium Frequency
~25 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen