Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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 -228 to 228 - 1 and the result is guaranteed to be at most 231 - 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

My code:

class Solution(object):
    def fourSumCount(self, A, B, C, D):
        """
        :type A: List[int]
        :type B: List[int]
        :type C: List[int]
        :type D: List[int]
        :rtype: int
        """
        length=len(A)
        if length==0:
            return 0
        sum_dict1={}
        for i in range(length):
            for j in range(length):
                sum_value=A[i]+B[j]
                if sum_value not in sum_dict1:
                    sum_dict1[sum_value]=1
                else:
                    sum_dict1[sum_value]+=1
        sum_dict2={}
        for i in range(length):
            for j in range(length):
                sum_value=C[i]+D[j]
                if sum_value not in sum_dict2:
                    sum_dict2[sum_value]=1
                else:
                    sum_dict2[sum_value]+=1
        overall=0
        for key in sum_dict1:
            key2=-key
            if key2 in sum_dict2:
                overall+=sum_dict1[key]*sum_dict2[key2]
        #print(sum_dict1)
        #print(sum_dict2)
        return overall
        

Solution: https://leetcode.com/problems/4sum-ii/