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
n
.n
is at least 1.We can use a HashMap to store the sums of all possible pairs from two of the arrays (nums1
and nums2
), and then for each possible pair sum from the remaining two arrays (nums3
and nums4
), we check if the negation of that sum exists in the HashMap.
nums1
and nums2
.nums3
and nums4
, calculate the sum of each pair and check if the negation of that sum exists in the HashMap. If it exists, it means there is a corresponding pair in nums1
and nums2
that can make the overall sum zero.import java.util.HashMap;
import java.util.Map;
public class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> sumCountMap = new HashMap<>();
// Calculate all pair sums from nums1 and nums2, and store them in the map
for (int num1 : nums1) {
for (int num2 : nums2) {
int sum = num1 + num2;
sumCountMap.put(sum, sumCountMap.getOrDefault(sum, 0) + 1);
}
}
int count = 0;
// Calculate all pair sums from nums3 and nums4, and check against the map
for (int num3 : nums3) {
for (int num4 : nums4) {
int sum = num3 + num4;
count += sumCountMap.getOrDefault(-sum, 0);
}
}
return count;
}
}
The time complexity of the algorithm is as follows:
nums1
and nums2
.nums3
and nums4
.Thus, the overall time complexity is O(n^2) + O(n^2) = O(n^2)
.
The space complexity is O(n^2)
for storing the pair sums in the HashMap.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?