Prefix-sum + hashing
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A prefix sum is a running total written down at every step, like a bank passbook balance. The difference between two balances tells you the total between those moments. Adding a hash map lets you find such stretches without trying every pair of start and end points.
Practical use cases
- Web app: Passbook stretch with zero net change. A banking app wants to flag any period where the money in and out cancelled exactly to zero. Instead of checking every pair of dates, it stores the running balance in a map and notices when the same balance appears twice. Two equal balances mean the transactions between them add up to zero.
- Web app: Sales between two dates. A report page lets the owner pick any two dates and see total sales. Keeping a running total per day makes any range answer one subtraction. Nobody adds up 365 daily rows again and again, so the date pickers feel snappy even when users change them repeatedly.
- System: Range queries on logs. A monitoring tool stores cumulative request counts per minute. To know how many requests arrived between 10:15 and 10:40, it subtracts two stored numbers instead of adding 25 rows again and again. A "last 30 minutes" slider on the dashboard updates smoothly as you drag it.
The story: The Passbook Trick
Grandpa Bhaskar's old bank passbook listed every deposit and withdrawal: +2000, +3000, -2000, +4000... At the end of each line, the bank stamped the running balance. One day Mira asked, "Dadaji, was there ever a stretch of days where you gained exactly 5000 rupees in total?"
Grandpa started adding up pieces of the passbook: days 1 to 2, then 1 to 3, then 2 to 3... his pencil ran dry. Mira had a better idea. "Look at the running balance column the bank already wrote. If the balance today is 7000 and a stretch gained 5000, then before that stretch began the balance must have been 2000. Just check whether the balance was ever 2000 earlier!"
Together they kept a small note of every balance seen and the day it first appeared. For each new day, one glance at the note told them whether a 5000-gain stretch ended today and how long it was. Using the earliest day for each balance gives the longest stretch. This combination, the running total (prefix sum) plus a hash map to look up earlier totals, solves a whole family of subarray problems in a single pass.
How to spot this problem, and where you need it
You repeatedly need the total of a stretch of consecutive items, or want to find a stretch that adds up to a target, and re-adding each stretch is too slow.
Signs you need it
- The problem says "subarray", "continuous stretch", "sum between i and j" or "net zero".
- You use two loops, one for the start and one for the end, and add up the items in between each time.
- The same range totals are requested many times, for example a date-range report where users keep changing dates.
Where to use it in a project
- Statement pages and ledgers where users pick a date range and expect the total at once.
- Fraud or audit checks looking for stretches of transactions that balance out to a given figure.
The solution
Walk through the data and keep a running total. Store each running total in a hash map with where it was seen. To find a stretch that adds up to a target, at each step ask the map whether the running total minus the target was seen earlier. If yes, the items after that earlier point up to now add up to the target. One pass does the whole job.
Payoff: Before: checking every start and end pair, millions of additions. After: one pass with one lookup per item.
Explain it like I am 8
Say you walk along a path and write down how many steps you have walked in total at each lamp-post. To know how far you walked between two lamp-posts, just subtract their two numbers. A hash map helps you instantly find an earlier lamp-post with the number you need.
How it works, step by step
- Keep a running total (
pre) of the numbers so far. - Create a map that remembers the first index at which each running total appeared. Start it with
0 → -1(the total before any number). - At index
i, a stretch ending here adds tokif an earlier total equalspre - k. Look it up in the map. - If found at index
j, the stretch isj+1 .. iand its length isi - j. Keep the longest. - Store
prein the map only if it is new, so the earliest index (longest stretch) is kept.
The code in four languages
PHP
<?php
// Longest stretch of numbers (negatives allowed) whose sum is exactly $k.
function longestSubarraySum(array $nums, int $k): int {
$first = [0 => -1]; // running total => earliest index where it appeared
$pre = 0;
$best = 0;
foreach ($nums as $i => $x) {
$pre += $x; // running total up to i
$need = $pre - $k; // total that must have come before
if (array_key_exists($need, $first)) {
$best = max($best, $i - $first[$need]); // stretch (first+1 .. i)
}
if (!array_key_exists($pre, $first)) $first[$pre] = $i; // keep the earliest index only
}
return $best;
}
echo longestSubarraySum([2, 3, -2, 4, -1, 1], 5) . "\n"; // 5 (3, -2, 4, -1, 1)
echo longestSubarraySum([1, 2, 3], 7) . "\n"; // 0 (no such stretch)
JavaScript
// Longest stretch of numbers (negatives allowed) whose sum is exactly k.
function longestSubarraySum(nums, k) {
const first = new Map([[0, -1]]); // running total => earliest index where it appeared
let pre = 0, best = 0;
nums.forEach((x, i) => {
pre += x; // running total up to i
const need = pre - k; // total that must have come before
if (first.has(need)) {
best = Math.max(best, i - first.get(need)); // stretch (first+1 .. i)
}
if (!first.has(pre)) first.set(pre, i); // keep the earliest index only
});
return best;
}
console.log(longestSubarraySum([2, 3, -2, 4, -1, 1], 5)); // 5 (3, -2, 4, -1, 1)
console.log(longestSubarraySum([1, 2, 3], 7)); // 0 (no such stretch)Java
import java.util.*;
public class Main {
// Longest stretch of numbers (negatives allowed) whose sum is exactly k.
static int longestSubarraySum(int[] nums, int k) {
Map<Integer, Integer> first = new HashMap<>();
first.put(0, -1); // running total => earliest index where it appeared
int pre = 0, best = 0;
for (int i = 0; i < nums.length; i++) {
pre += nums[i]; // running total up to i
int need = pre - k; // total that must have come before
if (first.containsKey(need)) {
best = Math.max(best, i - first.get(need)); // stretch (first+1 .. i)
}
first.putIfAbsent(pre, i); // keep the earliest index only
}
return best;
}
public static void main(String[] args) {
System.out.println(longestSubarraySum(new int[]{2, 3, -2, 4, -1, 1}, 5)); // 5 (3, -2, 4, -1, 1)
System.out.println(longestSubarraySum(new int[]{1, 2, 3}, 7)); // 0 (no such stretch)
}
}Go
package main
import "fmt"
// longestSubarraySum returns the longest stretch of numbers (negatives allowed) whose sum is exactly k.
func longestSubarraySum(nums []int, k int) int {
first := map[int]int{0: -1} // running total => earliest index where it appeared
pre, best := 0, 0
for i, x := range nums {
pre += x // running total up to i
need := pre - k // total that must have come before
if j, ok := first[need]; ok {
best = max(best, i-j) // stretch (j+1 .. i)
}
if _, ok := first[pre]; !ok {
first[pre] = i // keep the earliest index only
}
}
return best
}
func main() {
fmt.Println(longestSubarraySum([]int{2, 3, -2, 4, -1, 1}, 5)) // 5 (3, -2, 4, -1, 1)
fmt.Println(longestSubarraySum([]int{1, 2, 3}, 7)) // 0 (no such stretch)
}Time: O(n) · Extra space: O(n). One pass with constant-time map lookups, and the map can hold up to n different running totals.
Watch out for
- Forgetting to seed the map with
0 → -1, which misses stretches that start at the very first number. - Overwriting an existing total with a later index, which shortens the answer. Keep the first index for the longest stretch.
- Using a sliding window when numbers can be negative: shrinking the window no longer reduces the sum predictably.
Quick check
- A stretch ending at i adds to k. What must the running total just before the stretch be?
- pre + k
- pre - k
- k
- Why do we start the map with 0 → -1?
- To handle stretches that begin at the first number
- To avoid negative numbers
- To make the map bigger
- To find the LONGEST stretch, which index do we store per total?
- The latest
- The earliest
- A random one