Skip to content

Commit 97f67a2

Browse files
authored
Create 4sum-ii.py
1 parent 4b95c81 commit 97f67a2

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Python/4sum-ii.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: O(n^2)
2+
# Space: O(n^2)
3+
4+
# Given four lists A, B, C, D of integer values,
5+
# compute how many tuples (i, j, k, l) there are
6+
# such that A[i] + B[j] + C[k] + D[l] is zero.
7+
#
8+
# To make problem a bit easier, all A, B, C, D have same length of N where 0 <= N <= 500.
9+
# All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.
10+
#
11+
# Example:
12+
#
13+
# Input:
14+
# A = [ 1, 2]
15+
# B = [-2,-1]
16+
# C = [-1, 2]
17+
# D = [ 0, 2]
18+
#
19+
# Output:
20+
# 2
21+
#
22+
# Explanation:
23+
# The two tuples are:
24+
# 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
25+
# 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
26+
27+
class Solution(object):
28+
def fourSumCount(self, A, B, C, D):
29+
"""
30+
:type A: List[int]
31+
:type B: List[int]
32+
:type C: List[int]
33+
:type D: List[int]
34+
:rtype: int
35+
"""
36+
A_B_sum = collections.Counter(a+b for a in A for b in B)
37+
return sum(A_B_sum[-c-d] for c in C for d in D)

0 commit comments

Comments
 (0)