Problem Description
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. Since the answer can be very large, return it modulo 10^9 + 7.
Key Insights
- Use a frequency counter for elements since arr[i] is in the range [0, 100].
- Iterate through all possible combinations of numbers x, y, and z with x <= y <= z.
- For each valid triplet (x, y, z) that sums to target, count the number of ways using combinatorial formulas:
- All distinct: count[x] * count[y] * count[z].
- Two numbers the same: use nC2 for the repeated element.
- All three the same: use nC3.
- Use modulo arithmetic (MOD = 10^9 + 7) at every step to avoid overflow.
Space and Time Complexity
Time Complexity: O(M^2), where M = 101 (the range of possible numbers), which is efficient given the constraints.
Space Complexity: O(M) for the frequency array.
Solution
The solution first counts the frequency of each number in the array. Then it iterates through all valid triplets (x, y, z) (with x <= y <= z) and checks if they sum up to the target. Depending on whether x, y, and z are distinct or have duplicates, the combination count is computed accordingly:
- If x, y, and z are all the same, compute the combination as nC3.
- If only two are the same, compute as nC2 multiplied by the count of the third number.
- If all are distinct, use the direct product of the counts. This covers all cases while applying the modulo operation to the result.