4Sum II LeetCode Solution

Problem – 4Sum II

Given four integer arrays nums1nums2nums3, 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

Constraints:

  • n == nums1.length
  • n == nums2.length
  • n == nums3.length
  • n == nums4.length
  • 1 <= n <= 200
  • -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228

4Sum II LeetCode Solution in Java

public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
	var pairCountBySum = new HashMap<Integer, Integer>();
	
	Arrays.stream(nums1)
		  .forEach(num1 -> Arrays.stream(nums2)
							     .forEach(num2 -> pairCountBySum.compute(num1 + num2, (k, sumCount) -> sumCount == null ? 1 : ++sumCount)));
		  
	return Arrays.stream(nums3)
				 .map(num3 -> Arrays.stream(nums4)
								    .map(num4 -> pairCountBySum.getOrDefault(-(num3 + num4), 0))
									.sum())
				 .sum();
}

4Sum II LeetCode Solution in Python

def fourSumCount(self, A, B, C, D):
    AB = collections.Counter(a+b for a in A for b in B)
    return sum(AB[-c-d] for c in C for d in D)

4Sum II LeetCode Solution in C++

    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        int res = 0;
        unordered_map<int, int> AB;
        for (int a : A)
            for (int b : B)
                AB[a + b]++;
        for (int c : C)
            for (int d : D)
                res += AB[-c - d];
        return res;
    }
4Sum II LeetCode Solution Review:

In our experience, we suggest you solve this 4Sum II LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the 4Sum II LeetCode Solution

Find on LeetCode

Conclusion:

I hope this 4Sum II LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.