We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent a89fe6e commit e60b21eCopy full SHA for e60b21e
Python/3sum-with-multiplicity.py
@@ -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