454. 4Sum II LeetCode Solution

In this guide, you will get 454. 4Sum II LeetCode Solution with the best time and space complexity. The solution to Sum II problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Sum II solution in C++
  4. Sum II solution in Java
  5. Sum II solution in Python
  6. Additional Resources
454. 4Sum II LeetCode Solution image

Problem Statement of Sum 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

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

Complexity Analysis

  • Time Complexity: O(n^2)
  • Space Complexity: O(n^2)

454. 4Sum II LeetCode Solution in C++

class Solution {
 public:
  int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3,
                   vector<int>& nums4) {
    int ans = 0;
    unordered_map<int, int> count;

    for (const int a : nums1)
      for (const int b : nums2)
        ++count[a + b];

    for (const int c : nums3)
      for (const int d : nums4)
        if (const auto it = count.find(-c - d); it != count.cend())
          ans += it->second;

    return ans;
  }
};
/* code provided by PROGIEZ */

454. 4Sum II LeetCode Solution in Java

class Solution {
  public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (final int a : nums1)
      for (final int b : nums2)
        count.merge(a + b, 1, Integer::sum);

    for (final int c : nums3)
      for (final int d : nums4)
        if (count.containsKey(-c - d))
          ans += count.get(-c - d);

    return ans;
  }
}
// code provided by PROGIEZ

454. 4Sum II LeetCode Solution in Python

class Solution:
  def fourSumCount(self, nums1: list[int], nums2: list[int],
                   nums3: list[int], nums4: list[int]) -> int:
    count = collections.Counter(a + b for a in nums1 for b in nums2)
    return sum(count[-c - d] for c in nums3 for d in nums4)
# code by PROGIEZ

Additional Resources

See also  15. 3Sum LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.