4Sum II - Easy O(N^2) solution using HashMap
Problem Statement:
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:
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.length
n == nums2.length
n == nums3.length
n == nums4.length
1 <= n <= 200
-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
Solution:
Create a hashmap H of all possible sums of nums1
and nums2
in O(N^2) time.
Then traverse nums3
Xnums4
in O(N^2) time and each time check membership in H.
Easy-peasy!
C++ version:
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
int n = nums1.size(), res=0;
unordered_map<int,int> H;
for (int n1: nums1) for (int n2: nums2) H[n1+n2]++;
for (int n3: nums3) for (int n4: nums4) if (H.count(-(n3+n4))) res+=H[-(n3+n4)];
return res;
}
};
Python version:
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
H = collections.defaultdict(int)
res = 0
for n1 in nums1:
for n2 in nums2:
H[n1+n2]+=1
for n3 in nums3:
for n4 in nums4:
if -(n3+n4) in H:
res += H[-(n3+n4)]
return res