
Sponsored
Sponsored
This approach leverages hash maps to efficiently count and use pair sums. First, we compute all possible sums between arrays nums1 and nums2, storing them in a hash map along with their count. Then, we iterate over pairs of nums3 and nums4, checking how many complements (to form a sum of zero) exist in the hash map.
Time Complexity: O(n^2), with each pair calculation taking constant time.
Space Complexity: O(n^2), using space for hash map storage.
1from collections import Counter
2
3def fourSumCount(nums1, nums2, nums3, nums4):
4 sum_map = Counter(a + b for a in nums1 for b in nums2)
5 return sum(sum_map[-c - d] for c in nums3 for d in nums4)
6The Python solution utilizes a Counter from the collections module to hold pair sums from nums1 and nums2. It then calculates the sum of occurrences for complementary sums involving nums3 and nums4, giving the total count of zero-sum tuples.