Skip to content

Commit e60b21e

Browse files
authored
Create 3sum-with-multiplicity.py
1 parent a89fe6e commit e60b21e

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Python/3sum-with-multiplicity.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Time: O(n^2), n is the number of disctinct A[i]
2+
# Space: O(n)
3+
4+
import collections
5+
import itertools
6+
7+
8+
class Solution(object):
9+
def threeSumMulti(self, A, target):
10+
"""
11+
:type A: List[int]
12+
:type target: int
13+
:rtype: int
14+
"""
15+
count = collections.Counter(A)
16+
result = 0
17+
for i, j in itertools.combinations_with_replacement(count, 2):
18+
k = target - i - j
19+
if i == j == k:
20+
result += count[i] * (count[i]-1) * (count[i]-2) // 6
21+
elif i == j != k:
22+
result += count[i] * (count[i]-1) // 2 * count[k]
23+
elif max(i, j) < k:
24+
result += count[i] * count[j] * count[k]
25+
return result % (10**9 + 7)

0 commit comments

Comments
 (0)