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 < nnums1[i] + nums2[j] + nums3[k] + nums4[l] == 0n of each array?
1 <= n <= 200.(i, j, k, l).n (e.g., if n = 200, then (200^4 = 1.6 \times 10^{10}) operations).nums1 and nums2 and their counts.nums3 and nums4, check if the negative of their sum exists in the hash map.Here is the implementation of the optimized approach:
from collections import defaultdict
def fourSumCount(nums1, nums2, nums3, nums4):
count_map = defaultdict(int)
# Store sums of all pairs from nums1 and nums2
for a in nums1:
for b in nums2:
count_map[a + b] += 1
count = 0
# Check sums of all pairs from nums3 and nums4
for c in nums3:
for d in nums4:
target = -(c + d)
if target in count_map:
count += count_map[target]
return count
# Example usage
nums1 = [1, 2]
nums2 = [-2, -1]
nums3 = [-1, 2]
nums4 = [0, 2]
print(fourSumCount(nums1, nums2, nums3, nums4)) # Output: 2
(a+b) in count_map from nums1 and nums2 takes (O(n^2)).(c+d) from nums3 and nums4 against count_map also takes (O(n^2)).This approach leverages hash map lookups for efficient counting and ensures we can handle larger inputs more effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?