def fourSumCount(self, A, B, C, D):
AB = collections.Counter(a+b for a in A for b in B)
return sum(AB[cd] for c in C for d in D)
Easy 2 lines O(N^2) Python


@slcott
collections
isn't a library. It's a module. And it's part of the Python standard library, just like the dict you're using.



@StefanPochmann How does the code get us the sum of 0? Can you give some explanation?

# O(n**2) time, O(n**2) space def fourSumCount(self, A, B, C, D): count = 0 num_dict = {} for i in C: for j in D: s = i + j if s in num_dict: num_dict[s] += 1 else: num_dict[s] = 1 for i in range(len(A)): for j in range(len(B)): target = 0  (A[i]+B[j]) if target in num_dict: count += num_dict[target] return count


@Lakeriver Please check https://docs.python.org/2/library/collections.html, cd is calculated and then check if it is in the colletions.Counter()