imashutosh51

4 sum II

Oct 16th, 2022 (edited)
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. '''
  2. For any valid quadruple (i, j, k, l), we must have:
  3. nums1[i] + nums2[j] + nums3[k] + nums4[l] = 0
  4.  
  5. This can be rearranged as:
  6. (nums1[i] + nums2[j]) = -(nums3[k] + nums4[l])
  7.  
  8. First, we compute all possible sums of nums1 and nums2 and store their frequencies in a hashmap.
  9. Then, for each sum of nums3 and nums4, we check if its negative exists in the hashmap.
  10. If it exists, we add its frequency to the answer.
  11.  
  12. This counts all valid quadruples efficiently in O(n^2) time.
  13. '''
  14.  
  15. class Solution:
  16.     def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
  17.         dict1={}
  18.         for i in range(len(nums1)):
  19.             for j in range(len(nums2)):
  20.                 cur=nums1[i]+nums2[j]
  21.                 dict1[cur]=dict1.get(cur,0)+1
  22.  
  23.         print(dict1)
  24.         ans=0
  25.         for i in range(len(nums3)):
  26.             for j in range(len(nums4)):
  27.                 cur=nums3[i]+nums4[j]
  28.                 if 0-cur in dict1:
  29.                     ans+=dict1[0-cur]
  30.         return ans
  31.        
Advertisement
Add Comment
Please, Sign In to add comment