Advertisement
imashutosh51

4 sum II

Oct 16th, 2022
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. /*
  2. It is a fact that for any such (i,j,k,l) ith + jth element must be equal to negative of kth +lth element.
  3. we are adding all i and j and put them into mp1 and vice versa for kth and lth elements.
  4. Now we are checking for total numbers of groups possible.
  5. */
  6. class Solution {
  7. public:
  8.     int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
  9.         unordered_map<int,int> mp1,mp2;
  10.         int n=nums1.size();
  11.         for(int i=0;i<n;i++){
  12.             for(int j=0;j<n;j++){
  13.                 mp1[nums1[i]+nums2[j]]++;
  14.             }
  15.         }
  16.         for(int i=0;i<n;i++){
  17.             for(int j=0;j<n;j++){
  18.                 mp2[nums3[i]+nums4[j]]++;
  19.             }
  20.         }
  21.         int ans=0;
  22.         for(auto itr:mp1){
  23.             if(mp2[-(itr.first)]) ans+= itr.second*(mp2[-(itr.first)]);
  24.         }
  25.         return ans;
  26.        
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement