{x}
blog image

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

 

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

Solution Explanation for 4Sum II

This problem asks to find the number of tuples (i, j, k, l) such that nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0. A naive approach would involve four nested loops, resulting in O(n⁴) time complexity, which is inefficient for larger inputs. The optimal solution utilizes a hash table to significantly reduce the time complexity.

Approach:

The core idea is to break down the problem into two parts:

  1. Precompute sums: Calculate all possible sums of nums1[i] + nums2[j] and store their frequencies in a hash map (or dictionary). The key will be the sum, and the value will be the number of times that sum occurs.

  2. Count complementary pairs: Iterate through nums3 and nums4. For each pair nums3[k] + nums4[l], check if the negative of this sum -(nums3[k] + nums4[l]) exists as a key in the hash map. If it does, add its frequency (value) to the final count. This is because if nums1[i] + nums2[j] == -(nums3[k] + nums4[l]), then nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0.

Time Complexity Analysis:

  • Step 1 (Precompute sums): This step involves nested loops iterating through nums1 and nums2, resulting in O(n²) time complexity. The hash map operations (insertion and lookup) are typically O(1) on average.

  • Step 2 (Count complementary pairs): Similar to Step 1, this step involves nested loops through nums3 and nums4 (O(n²)). Hash map lookups are again O(1) on average.

Therefore, the overall time complexity is O(n²). This is a significant improvement over the naive O(n⁴) approach.

Space Complexity Analysis:

The hash map used to store the frequencies of sums in Step 1 can, in the worst case, store O(n²) unique sums. Thus, the space complexity is O(n²).

Code Examples:

The code examples provided demonstrate the approach in various programming languages. They all follow the same logic:

  1. Initialize a hash map (or dictionary).
  2. Compute and store the frequencies of sums from nums1 and nums2.
  3. Iterate through nums3 and nums4, looking up complementary sums in the hash map and accumulating the count.
  4. Return the final count.

Example (Python):

from collections import Counter
 
class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        sum_counts = Counter(a + b for a in nums1 for b in nums2)
        count = 0
        for c in nums3:
            for d in nums4:
                count += sum_counts.get(-(c + d), 0)  # Get frequency or 0 if not found
        return count

The other language examples follow a similar structure, adapting the syntax and data structures to their respective languages. They all achieve the same O(n²) time and O(n²) space complexity.