454. 4Sum II
DifficultyMedium
Description
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
Example 1:
Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] Output: 2 Explanation: The two tuples are: 1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
Example 2:
Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] Output: 1
Constraints:
n == nums1.lengthn == nums2.lengthn == nums3.lengthn == nums4.length1 <= n <= 200-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
Solutions
Solution 1: Hash Table
Thinking
Four nested loops are \(O(n^4)\) and \(n\le 200\) is too large. A zero sum splits as \((a+b)+(c+d)=0\).
Count every pair sum from \(\textit{nums1}\) and \(\textit{nums2}\), then enumerate \(c,d\) and add \(\textit{cnt}[-(c+d)]\).
The \(O(n^2)\) pair enumeration turns a 4-tuple search into a hash lookup.
We can add the elements \(a\) and \(b\) in arrays \(\textit{nums1}\) and \(\textit{nums2}\) respectively, and store all possible sums in a hash table \(\textit{cnt}\), where the key is the sum of the two numbers, and the value is the count of the sum.
Then we iterate through the elements \(c\) and \(d\) in arrays \(\textit{nums3}\) and \(\textit{nums4}\), let \(c+d\) be the target value, then the answer is the cumulative sum of \(\textit{cnt}[-(c+d)]\).
The time complexity is \(O(n^2)\), and the space complexity is \(O(n^2)\), where \(n\) is the length of the array.
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |