Prefix & Suffix — the shape behind dozens of interview problems.
TL;DR
Precompute cumulative arrays so range queries answer in O(1). Preprocess O(n); query O(1).
When to reach for Prefix & Suffix
- Many range sum / product / min queries.
- You need "everything except index i" in linear time.
- Stateless transforms on immutable arrays.
Scenario variants (legal, original)
- Exclusive Revenue — product of array except self.
- Range Tally — sum over [l, r].
- Running Balance — detect first index where total flips sign.
Prefix & Suffix in Python
def range_sum(nums: list[int]) -> list[int]:
pre = [0]
for v in nums:
pre.append(pre[-1] + v)
return pre # pre[r+1] - pre[l] gives sum of nums[l..r]See language-specific tabs at /languages/python/patterns and the SQL variant at /languages/sql/patterns.
Common bugs
- Off-by-one between prefix length n+1 and array length n.
- Using integer types that overflow for products (switch to explicit big-int if needed).
- Recomputing prefixes inside the query loop — defeats the whole pattern.
Related patterns
Frequently asked questions
- What is the prefix & suffix pattern?
- Prefix & Suffix is precompute cumulative arrays so range queries answer in o(1). Preprocess O(n); query O(1).
- When should I use prefix & suffix?
- Use it when: Many range sum / product / min queries. You need "everything except index i" in linear time. Stateless transforms on immutable arrays.
- What are the most common prefix & suffix bugs?
- Off-by-one between prefix length n+1 and array length n. Using integer types that overflow for products (switch to explicit big-int if needed). Recomputing prefixes inside the query loop — defeats the whole pattern.
- What problems use the prefix & suffix pattern?
- Representative scenarios: Exclusive Revenue — product of array except self. Range Tally — sum over [l, r]. Running Balance — detect first index where total flips sign.
- Is prefix & suffix on the Blind 75?
- Yes — Prefix & Suffix is one of the core patterns behind the Blind 75 list. See /blind-75 for the complete mapping.
Run the free diagnostic.
Ten-minute patterns quiz. No card. Personalized loop starts on the other side.