3Sum With Multiplicity
Problem Statement
You are given an integer array arr and a number target.
Count the triplets of positions i < j < k with arr[i] + arr[j] + arr[k] == target.
This time repeats do count: if the same values can be picked from different positions, each choice of positions is a separate triplet. The answer can be huge, so return it modulo 10^9 + 7.
An integer array arr and an integer target.
One integer: the number of position-triplets i < j < k whose values add up to target, modulo 10^9 + 7.
Values (1, 2, 5) can be picked 2 × 2 × 2 = 8 ways, (1, 3, 4) also 8 ways, (2, 2, 4) 1 × 2 = 2 ways, and (2, 3, 3) 2 × 1 = 2 ways. Total 20.
Only (1, 2, 2) works. Pick one of the two 1s (2 ways) and two of the four 2s (6 ways): 2 × 6 = 12.
1 + 2 + 3 = 6, and there is only one way to pick it.
- • 3 ≤ arr.length ≤ 3000
- • 0 ≤ arr[i] ≤ 100
- • 0 ≤ target ≤ 300
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Three loops over positions; count matches
Sort; fix i; on a match, count equal runs (cl × cr, or C(m, 2) if both sides are equal)
Count copies of each value; two pointers over ≤ 101 distinct values; combine with combinatorics
Try every i < j < k and count the ones whose values add up to target. Take the count modulo 10^9 + 7 at the end.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Two Pointers translate into production architectures and low-level memory mechanics.
Circular Buffer & Ring Queue
Two pointer read/write head synchronization in production memory pools.
Pointers vs References Deep Dive
Pointer arithmetic, dereferencing semantics, and memory layout behind in-place array passes.
const Correctness & East-Const
Passing read-only spans with const int* without copying buffers.