LeetCode 454. 4Sum II
Question
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
Example 1:
1 | Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] |
Example 2:
1 | Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] |
Constraints:
n == nums1.length
n == nums2.length
n == nums3.length
n == nums4.length
1 <= n <= 200
-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
Source: https://leetcode.com/problems/4sum-ii/
Solution
The two differences of this problem from LeetCode 18. 4Sum are:
- 4 elements in the tuple are from 4 arrays respectively
- we do not care about the content of each qualified tuple, but the number of qualified tuples.
Thus, we use a double loop to get all pairs between array1 and array2, and all pairs between array3 and array4. Then we traverse the map to calculate the number of qualified combinations.
1 | // the key difference from 4Sum is that indexes in 4 arrays are independent |
LeetCode 454. 4Sum II