Technique · CP 2400+
FFT / NTT Convolution (and Walsh-Hadamard)
Multiply polynomials (convolve count arrays) in O(n log n). Use it whenever the answer is c[k] = sum of a[i]*b[k-i]: counting pair sums, matching with wildcards or mismatches, polynomial products. XOR/AND/OR convolutions use the Walsh-Hadamard transform.
0/9 solved
Recognise it
The signal
for every k, count pairs (i, j) with i + j = k (or values summing to k)
1Brute force
Direct convolution: O(n2).
2The observation
All index pairs get combined.
3Why it works
Evaluating at roots of unity turns convolution into pointwise multiplication.
Reach for it when
- +n up to 2e5 with an O(n2) pair loop
- +string matching with wildcards, or mismatch counts for every alignment
- +answer modulo 998244353
Not when
- ×only one k is asked (two pointers / hashing)
- ×the modulus is not NTT-friendly (three-prime NTT or split FFT)
Practice
- Apples and BananasCSESHard
- One Bit PositionsCSESHard
- Signal ProcessingCSESHard
- Bit SubstringsCSESHard
- All Subarray XorsCSESHard
- Fuzzy SearchCodeforces2500
- Nikita and Order StatisticsCodeforces2300
- Red-White FenceCodeforces2500
- Substring SearchCodeforces2900
Pitfalls
Misconceptions
- !floating-point FFT loses precision when products exceed ~1e15
Go deeper2 combinations · resources
Combinations
FFT / NTT Convolution (and Walsh-Hadamard)+String Matching (KMP / Z / Rabin-Karp)
pattern matching with wildcards, or counting mismatches/near-matches for every alignment
- FFT / NTT Convolution (and Walsh-Hadamard):
- for each alphabet letter, convolve the indicator arrays to count matches at every shift
- String Matching (KMP / Z / Rabin-Karp):
- the matching-per-shift question
FFT / NTT Convolution (and Walsh-Hadamard)+Prefix Sum
for every k, the number of subarrays with exactly k elements satisfying a predicate
- FFT / NTT Convolution (and Walsh-Hadamard):
- convolve the count array with its reverse to count subarrays with exactly k good elements, for all k
- Prefix Sum:
- count the prefixes having each number of 'good' elements