[
two pointers
hash table
counter
2sum
]
Leetcode 0923. 3Sum With Multiplicity
https://leetcode.com/problems/3sum-with-multiplicity
Let us calculate Counter(arr), that is how what is frequency of each number and then check 3 cases:
- All numbers
i < j < kar different: then we can check all possible permutations for numbersiandjand then check that fork = target - i - jwe havei < j < k. - For numbers
i, j, kwe havei = j != k. Then we havec[i]*(c[i]-1)*c[target - 2*i]//2number of options. Why? Because we need to chooseielement twice, this is number of combinations with2elements fromc[i]elements. Note, that I did not specify which of three indexes here is smaller and which is bigger, so here we cover all cases where exactly2indexes are equal. - For numers
i, j, kwe havei = j = k. Here answer isc[i]*(c[i]-1)*(c[i]-2)//6: number of combinations with3elements fromc[i]elements.
Complexity: time complexity is O(n^2), where n is length of arr, because on first iteration we did O(n^2) and on second and third we did O(n). Space complexity is O(n).
class Solution:
def threeSumMulti(self, arr, target):
c = Counter(arr)
ans, M = 0, 10**9 + 7
for i, j in permutations(c, 2):
if i < j < target - i - j:
ans += c[i]*c[j]*c[target - i - j]
for i in c:
if 3*i != target:
ans += c[i]*(c[i]-1)*c[target - 2*i]//2
else:
ans += c[i]*(c[i]-1)*(c[i]-2)//6
return ans % M
If you like the solution, you can upvote it on leetcode discussion section: Problem 0923