publicclassSolution {
publicintfourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> map =new HashMap<>(); // HashMap to store sums of elements from nums1 and nums2int n = nums1.length;
int count = 0; // Counter to keep track of valid quadruples// Compute all possible sums of pairs from arrays nums1 and nums2for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int sum = nums1[i]+ nums2[j];
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
}
// Compute sums of pairs from arrays nums3 and nums4 and check for complements in the mapfor (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int sum = nums3[i]+ nums4[j];
if (map.containsKey(-sum)) {
count += map.get(-sum); // Increment count by the number of times the complement appears }
}
}
return count; // Return the total count of valid quadruples }
publicstaticvoidmain(String[] args) {
Solution sol =new Solution();
int[] nums1 = {1, 2};
int[] nums2 = {-2, -1};
int[] nums3 = {-1, 2};
int[] nums4 = {0, 2};
int result = sol.fourSumCount(nums1, nums2, nums3, nums4);
System.out.println("Number of quadruplets: "+ result); // Expected output: 2 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
deffourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
freq_map = defaultdict(int) # Dictionary to store sums of elements from nums1 and nums2 n = len(nums1)
count =0# Counter to keep track of valid quadruples# Compute all possible sums of pairs from arrays nums1 and nums2for num1 in nums1:
for num2 in nums2:
freq_map[num1 + num2] +=1# Compute sums of pairs from arrays nums3 and nums4 and check for complements in the dictionaryfor num3 in nums3:
for num4 in nums4:
target =-(num3 + num4)
if target in freq_map:
count += freq_map[target] # Increment count by the number of times the complement appearsreturn count # Return the total count of valid quadruples