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.
1function fourSumCount(nums1, nums2, nums3, nums4) {
2 const sumMap = new Map();
3 let count = 0;
4
5 for (let a of nums1) {
6 for (let b of nums2) {
7 const sum = a + b;
8 sumMap.set(sum, (sumMap.get(sum) || 0) + 1);
9 }
10 }
11
12 for (let c of nums3) {
13 for (let d of nums4) {
14 const complement = -(c + d);
15 if (sumMap.has(complement)) {
16 count += sumMap.get(complement);
17 }
18 }
19 }
20
21 return count;
22}
23
The JavaScript implementation employs a Map
to keep counts of the sums of elements from nums1
and nums2
. It then iterates through possible sums of nums3
and nums4
, checking how many can complement each other to form a zero total sum.