3Sum With Multiplicity - Problem

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 10⁹ + 7.

Note: We need to count the number of valid index triplets, not unique value triplets.

Input & Output

Example 1 — Basic Case
$ Input: arr = [1,1,2,2,3,3], target = 6
Output: 8
💡 Note: We need triplets where arr[i] + arr[j] + arr[k] = 6 and i < j < k. Valid combinations: 1+2+3=6. With indices: (0,2,4), (0,2,5), (0,3,4), (0,3,5), (1,2,4), (1,2,5), (1,3,4), (1,3,5) = 8 triplets
Example 2 — No Valid Triplets
$ Input: arr = [1,1,2,2,2,2], target = 5
Output: 12
💡 Note: Valid triplet: 1+2+2=5. We have 2 ways to choose first element (value 1) and C(4,2)=6 ways to choose two elements with value 2. Total: 2 × 6 = 12 triplets
Example 3 — Same Values
$ Input: arr = [2,2,2,2], target = 6
Output: 4
💡 Note: Need three 2's to sum to 6: 2+2+2=6. With 4 elements, we can choose 3 in C(4,3) = 4 ways: (0,1,2), (0,1,3), (0,2,3), (1,2,3)

Constraints

  • 3 ≤ arr.length ≤ 3000
  • 0 ≤ arr[i] ≤ 100
  • 0 ≤ target ≤ 300

Visualization

Tap to expand
3Sum With Multiplicity INPUT Array arr: 1 i=0 1 i=1 2 i=2 2 i=3 3 i=4 3 i=5 target = 6 Frequency Count: Val Count 1 2 2 2 3 2 ALGORITHM STEPS 1 Count Frequencies Build count map for arr 2 Iterate Unique Pairs For each i,j find k=target-i-j 3 Calculate Combinations Use C(n,r) for duplicates 4 Sum All Tuples Return count mod 10^9+7 Valid Triplets (sum=6): (1,2,3): 2x2x2 = 8 ways 1+2+3 = 6 [OK] Example combinations: arr[0]+arr[2]+arr[4]=1+2+3 arr[0]+arr[2]+arr[5]=1+2+3 arr[0]+arr[3]+arr[4]=1+2+3 ... (8 total) FINAL RESULT Output: 8 8 valid tuples found (satisfying i < j < k) All 8 Tuples: (0,2,4): 1+2+3=6 (0,2,5): 1+2+3=6 (0,3,4): 1+2+3=6 (0,3,5): 1+2+3=6 (1,2,4): 1+2+3=6 (1,2,5): 1+2+3=6 (1,3,4): 1+2+3=6 (1,3,5): 1+2+3=6 OK - Verified Key Insight: Use counting approach with frequency map instead of brute force O(n^3). For each unique triplet (a,b,c) where a+b+c=target, multiply their counts. Handle cases: all same, two same, all different. Time: O(n + k^2) where k = unique values | Space: O(k) for frequency map TutorialsPoint - 3Sum With Multiplicity | Optimal Solution (Counting Approach)
Asked in
Google 15 Facebook 12 Amazon 8
32.1K Views
Medium Frequency
~25 min Avg. Time
956 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen