3Sum With Multiplicity - 3 Sum over keys
Problem Statement:
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.
Example 3:
Input: arr = [2,1,3], target = 6 Output: 1 Explanation: (1, 2, 3) occured one time in the array so we return 1.
Constraints:
3 <= arr.length <= 3000
0 <= arr[i] <= 100
0 <= target <= 300
Solution:
class Solution {
public:
int threeSumMulti(vector<int>& arr, int target) {
int n = arr.size(), MAX=101, res=0, MOD=1000000007;
vector<int> frequencies(MAX, 0);
for (int k: arr) frequencies[k]++;
for (int x=0; x<MAX; x++)
{
for (int y=x+1; y<MAX; y++)
{
int z=target-x-y;
if (z>y && z<MAX)
{
long long a=frequencies[x], b=frequencies[y], c=frequencies[z];
long long d = a*b*c;
res += d%MOD;
res %= MOD;
}
}
}
for (int x=0; x<MAX; x++)
{
int y = target-2*x; //x,x,y
if (y>x && y<MAX)
{
long long a=frequencies[x], b=frequencies[y];
long long c = b * a * (a-1)/2;
res += c%MOD;
res %= MOD;
}
}
for (int x=0; x<MAX; x++)
{
int y = (target-x)/2; // x,y,y
if (y>x && (target-x)%2==0 && y<MAX)
{
long long a=frequencies[x], b=frequencies[y];
long long c = a * b * (b-1)/2;
res += c%MOD;
res %= MOD;
}
}
if (target%3==0)
{
int x=target/3;
long long a=frequencies[x];
long long b = a * (a-1) * (a-2)/6;
res += b%MOD;
res %= MOD;
}
return res;
}
};
TC: O(MAX^2)
SC: O(MAX)
where MAX
is the maximum value in the array (here 100).
Notice that the complexities do not depend on the length of arr
.