Skip to content

Commit 00babcc

Browse files
authored
Create 4Sum II.py
1 parent 585db8e commit 00babcc

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

4Sum II.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
'''
2+
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.
3+
4+
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.
5+
6+
Example:
7+
8+
Input:
9+
A = [ 1, 2]
10+
B = [-2,-1]
11+
C = [-1, 2]
12+
D = [ 0, 2]
13+
14+
Output:
15+
2
16+
17+
Explanation:
18+
The two tuples are:
19+
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
20+
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
21+
'''
22+
23+
class Solution(object):
24+
def fourSumCount(self, A, B, C, D):
25+
"""
26+
:type A: List[int]
27+
:type B: List[int]
28+
:type C: List[int]
29+
:type D: List[int]
30+
:rtype: int
31+
"""
32+
box = {}
33+
for a in A:
34+
for b in B:
35+
tmp = - a - b
36+
if tmp in box:
37+
box[tmp] += 1
38+
else:
39+
box[tmp] = 1
40+
41+
res = 0
42+
for c in C:
43+
for d in D:
44+
tmp = c + d
45+
if tmp in box:
46+
res += box[tmp]
47+
return res

0 commit comments

Comments
 (0)