4Sum II

 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 < n

nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

 


Example 1:


Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]

Output: 2

Explanation:

The two tuples are:

1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0

2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

Example 2:


Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]

Output: 1

 class Solution {

    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
       
        // Create a HashMap to store sum of pairs from nums1 and nums2
        // Key = sum of (a + b), Value = how many times this sum appears
        HashMap<Integer, Integer> map = new HashMap<>();
        int count = 0; // Final count of all valid quadruples

        // Step 1: Calculate all possible sums of elements from nums1 and nums2
        for (int a : nums1) {
            for (int b : nums2) {
                int sum = a + b;
                // Store the frequency of the sum in the map
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
        }

        // Step 2: For each pair from nums3 and nums4,
        // check if the negative of their sum exists in the map
        for (int c : nums3) {
            for (int d : nums4) {
                int target = -(c + d); // We want a + b + c + d = 0 → a + b = -(c + d)

                // If this target sum exists in the map,
                // it means we have found valid (a,b,c,d) combinations
                if (map.containsKey(target)) {
                    count += map.get(target); // Add how many times (a + b) = target
                }
            }
        }

        return count; // Return the total number of valid quadruples
    }
}


Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence