Leetcode Problem : 454. 4Sum II
Feb 3, 2022
You can find the problem here — 4 Sum II.
Algorithm
- Store all sums possible by using vectors — nums1 and nums2 in a hashmap
- Now we will search negative of all sums possible with vectors nums3 and nums4 in the hashmap.
- In this way our problem of finding sum 0 using 4 arrays is reduced to find sum 0 using 2 arrays.
- Space required O(n²) for hashmap.
- Time required O(n²) for forming sums using two vectors.
C++ Solution
#define ll int
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
map<ll,ll> m;
for(auto i:nums1)
for(auto j:nums2)
m[i+j]++;
ll ans = 0;
for(auto i:nums3)
for(auto j:nums4)
ans+=m[-(i+j)];
return ans;
}
};