923. 3Sum With Multiplicity

Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.

As the answer can be very large, return it modulo 109 + 7.

Example 1:
Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation:
Enumerating by the values (arr[i], arr[j], arr[k]):
(1, 2, 5) occurs 8 times;
(1, 3, 4) occurs 8 times;
(2, 2, 4) occurs 2 times;
(2, 3, 3) occurs 2 times.

Example 2:
Input: arr = [1,1,2,2,2,2], target = 5
Output: 12

Explanation:
arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:
We choose one 1 from [1,1] in 2 ways,
and two 2s from [2,2,2,2] in 6 ways.

Constraints:
3 <= arr.length <= 3000
0 <= arr[i] <= 100
0 <= target <= 300

Solution:
Combination formula = n! / (k! * (n-k)!)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution:
def threeSumMulti(self, arr: List[int], target: int) -> int:
MOD = 10**9 + 7
# 0 <= arr[i] <= 100
count = [0] * 101
# num of occurrency every number in arr
for x in arr:
count[x] += 1
res = 0
# all same
if target % 3 == 0:
x = target // 3
if 0<=x<=100:
res += count[x] * (count[x]-1) * (count[x]-2) / 6
res %= MOD
# all different
for x in range(101):
for y in range(x+1, 101):
z = target - x - y
if y < z <= 100:
res += count[x] * count[y] * count[z]
res %= MOD
# x == y != z
for x in range(101):
z = target - 2 * x
if x < z <= 100:
res += (count[x] * (count[x] - 1) / 2) * count[z]
res %= MOD
# x != y == z
for x in range(101):
if (target - x) % 2 == 0:
y = (target - x) // 2
if x < y <= 100:
res += (count[y] * (count[y] - 1) / 2) * count[x]
res %= MOD
return int(res)

references

Commentaires

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×