LeetCode 454: 4Sum II Solution

Master LeetCode problem 454 (4Sum II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

454. 4Sum II

Problem Explanation

Explanation

To solve this problem, we can use a hashmap to store the sums of all possible pairs of elements from the first two arrays nums1 and nums2. Then, we iterate through the remaining two arrays nums3 and nums4 and check if there exists a pair of elements whose sum equals the negation of the current sum of elements from nums3 and nums4.

  1. Create a hashmap to store sums of pairs from nums1 and nums2.
  2. Iterate through nums1 and nums2 to populate the hashmap with all possible sums.
  3. Iterate through nums3 and nums4, and for each sum in nums3 and nums4, check if the negation of that sum exists in the hashmap.
  4. Increment the count if a matching sum is found.

Time complexity: O(n^2)
Space complexity: O(n^2)

Solution Code

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer, Integer> map = new HashMap<>();
        int count = 0;
        
        for (int num1 : nums1) {
            for (int num2 : nums2) {
                int sum = num1 + num2;
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
        }
        
        for (int num3 : nums3) {
            for (int num4 : nums4) {
                int target = -1 * (num3 + num4);
                count += map.getOrDefault(target, 0);
            }
        }
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 454 (4Sum II)?

This page provides optimized solutions for LeetCode problem 454 (4Sum II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 454 (4Sum II)?

The time complexity for LeetCode 454 (4Sum II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 454 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 454 in Java, C++, or Python.

Back to LeetCode Solutions