4Sum II in Python

The 4Sum II problem asks us to find how many tuples (i, j, k, l) exist such that A[i] + B[j] + C[k] + D[l] equals zero, given four lists A, B, C, D of integers. This is an optimization problem that can be solved efficiently using a hash map approach.

Problem Understanding

Given four lists of integers with the same length N (0 ? N ? 500), we need to count tuples where the sum of elements at indices (i, j, k, l) from lists A, B, C, D respectively equals zero. For example, with A = [1, 2], B = [-2, -1], C = [-1, 2], D = [0, 2], we have two valid tuples ?

  • (0, 0, 0, 1): A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
  • (1, 1, 0, 0): A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

Algorithm Approach

The key insight is to split the problem into two parts. Instead of checking all four lists simultaneously, we ?

  • Calculate all possible sums from lists A and B, storing them in a hash map
  • For each sum from lists C and D, check if its negative exists in the hash map
  • If found, add the frequency count to our result

Implementation

class Solution:
    def fourSumCount(self, A, B, C, D):
        # Dictionary to store sums of A[i] + B[j] and their frequencies
        sums = {}
        
        # Calculate all possible sums from A and B
        for i in A:
            for j in B:
                sum_ab = i + j
                if sum_ab not in sums:
                    sums[sum_ab] = 1
                else:
                    sums[sum_ab] += 1
        
        counter = 0
        
        # For each sum from C and D, check if negative sum exists in sums
        for i in C:
            for j in D:
                target = -(i + j)  # We need A[i] + B[j] = -(C[k] + D[l])
                if target in sums:
                    counter += sums[target]
        
        return counter

# Test the solution
solution = Solution()
result = solution.fourSumCount([1, 2], [-2, -1], [-1, 2], [0, 2])
print(f"Number of valid tuples: {result}")

The output of the above code is ?

Number of valid tuples: 2

How It Works

The algorithm works in two phases ?

  1. Phase 1: Create a hash map storing all possible sums from lists A and B along with their frequencies
  2. Phase 2: For each combination from lists C and D, check if the negative of their sum exists in the hash map

Time and Space Complexity

  • Time Complexity: O(N²) where N is the length of each list
  • Space Complexity: O(N²) for storing the hash map of sums

Example Walkthrough

# Let's trace through the example step by step
A = [1, 2]
B = [-2, -1] 
C = [-1, 2]
D = [0, 2]

# Phase 1: Calculate sums from A and B
# A[0] + B[0] = 1 + (-2) = -1
# A[0] + B[1] = 1 + (-1) = 0  
# A[1] + B[0] = 2 + (-2) = 0
# A[1] + B[1] = 2 + (-1) = 1
# sums = {-1: 1, 0: 2, 1: 1}

solution = Solution()
print("Step-by-step trace:")
print(f"A = {A}, B = {B}, C = {C}, D = {D}")

sums = {}
for i in A:
    for j in B:
        sum_ab = i + j
        sums[sum_ab] = sums.get(sum_ab, 0) + 1
        print(f"A[{A.index(i)}] + B[{B.index(j)}] = {i} + {j} = {sum_ab}")

print(f"Sums dictionary: {sums}")

counter = 0
for i in C:
    for j in D:
        target = -(i + j)
        if target in sums:
            print(f"Found: C[{C.index(i)}] + D[{D.index(j)}] = {i} + {j} = {i+j}, need {target}")
            counter += sums[target]

print(f"Total valid tuples: {counter}")
Step-by-step trace:
A = [1, 2], B = [-2, -1], C = [-1, 2], D = [0, 2]
A[0] + B[0] = 1 + -2 = -1
A[0] + B[1] = 1 + -1 = 0
A[1] + B[0] = 2 + -2 = 0
A[1] + B[1] = 2 + -1 = 1
Sums dictionary: {-1: 1, 0: 2, 1: 1}
Found: C[0] + D[1] = -1 + 2 = 1, need -1
Found: C[1] + D[0] = 2 + 0 = 2, need -2
Total valid tuples: 2

Conclusion

The 4Sum II problem is efficiently solved using a hash map approach that reduces the time complexity from O(N?) to O(N²). By splitting the problem into two phases and storing intermediate sums, we can quickly count all valid tuples that sum to zero.

Updated on: 2026-03-25T08:10:29+05:30

853 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements