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: Count Valid Index TripletsInput: arr = [1,1,2,2,3,3], target = 6112233012345Need: arr[i] + arr[j] + arr[k] = 6 where i < j < kValid value combination: 1 + 2 + 3 = 6Valid index triplets:(0,2,4), (0,2,5), (0,3,4), (0,3,5)(1,2,4), (1,2,5), (1,3,4), (1,3,5)Result: 8🎯 Key Insight: Use frequency counting to avoid O(n³) brute force
Understanding the Visualization
1
Input
Array [1,1,2,2,3,3] and target 6
2
Find Valid Triplets
Find all i < j < k where arr[i] + arr[j] + arr[k] = 6
3
Count Results
Total of 8 valid index triplets
Key Takeaway
🎯 Key Insight: Count frequencies first, then calculate combinations for each unique triplet mathematically
Asked in
Google 15 Facebook 12 Amazon 8
32.0K 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