Problem

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -2**28 to 2**28 - 1 and the result is guaranteed to be at most 2**31 - 1.

Example:

Input: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2]

Output: 2

Explanation: The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

Thought Process

• brutal force won't work as 500**4 or 500**3 will exhaust most computers
• this will be an example of compromising space for time
• create a hash table of all possible sums of C and D (Space complexity of O(n**2))
• * need a ht of n**2 * k: sum results, v: appearances, time complexity is O(n**2)
• For sum of A, B:
• * find if -sum exists in ht, if it exists, return ht[-sum] * else return 0

White Board

Below is the white board:

Code

class Solution:

def _create_ht(self, num, ht):
assert(type(ht)) is dict
if num in ht:
ht[num] += 1
else:
ht[num] = 1
return ht

def four_sum(self, A, B, C, D):
ht = {}
for i in range(len(C)):
for j in range(len(D)):
self._create_ht(C[i] + D[j], ht)

res = 0
for i in range(len(A)):
for j in range(len(B)):
if - A[i] - B[j] in ht:
res += ht[- A[i] - B[j]]

return res

def test():
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
fs = Solution().four_sum(A,B,C,D)

print(fs)

test()


2

Complexity

• Time complexity is O(n**2) since I used a 2-level nested loop
• Space complexity is O(n**2) since I used a ht based off two indices

Optimization

I have yet to figure out a more optimal solution at this moment.