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
2
3
4
5
6
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:

1
2
Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
Output: 1

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:

  1. 4 elements in the tuple are from 4 arrays respectively
  2. 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// the key difference from 4Sum is that indexes in 4 arrays are independent
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
int len = nums1.length;
int result = 0;
// pair sum -> pair count
Map<Integer, Integer> pair12 = new HashMap<>();
Map<Integer, Integer> pair34 = new HashMap<>();
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
int sum12 = nums1[i] + nums2[j];
int sum34 = nums3[i] + nums4[j];
pair12.put(sum12, pair12.getOrDefault(sum12, 0) + 1);
pair34.put(sum34, pair34.getOrDefault(sum34, 0) + 1);
}
}
for (int sum12 : pair12.keySet()) {
int count12 = pair12.get(sum12);
int count34 = pair34.getOrDefault(-sum12, 0);
result += count12 * count34;
}
return result;
}
Author

Weihao Ye

Posted on

2022-03-10

Updated on

2022-03-10

Licensed under