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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int FourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
6 Dictionary<int, int> sumMap = new Dictionary<int, int>();
7 int count = 0;
8
9 foreach (int a in nums1) {
10 foreach (int b in nums2) {
11 int sum = a + b;
12 if (sumMap.ContainsKey(sum)) {
13 sumMap[sum]++;
14 } else {
15 sumMap[sum] = 1;
16 }
17 }
18 }
19
20 foreach (int c in nums3) {
21 foreach (int d in nums4) {
22 int complement = -(c + d);
23 if (sumMap.ContainsKey(complement)) {
24 count += sumMap[complement];
25 }
26 }
27 }
28
29 return count;
30 }
31}
32
This C# solution uses a Dictionary
to store the sums of pairs from the first two arrays. As it computes pairs from nums3
and nums4
, it sums any complementary values found in the dictionary to obtain total valid tuples.