STOP 05 · LINEAR STRUCTURES
Prefix Sums and Intervals
Prefix sums with a hash count O(n) time · O(n) space
Warm up with this one
LC 724Find Pivot IndexStuck? Peek at the approach
Compute the right-side sum from the total and the accumulated left-side sum instead of repeatedly summing ranges.
Key points
- A range sum is the difference of two prefix sums: sum(l..r) = pre[r+1] - pre[l]; allocate one extra slot with pre[0] = 0.
- When counting subarrays that sum to k, seed the map with {0: 1} for subarrays that start at index 0.
- For many range updates use a difference array (diff[l] += v, diff[r+1] -= v, then one prefix pass); to merge intervals, sort by left end first.
Common pitfalls
- Without the {0: 1} seed you miss every subarray that starts at index 0.
- Prefix sums overflow 32-bit integers easily; use long long in C++ and long in Java.
- Storing the current prefix before querying counts the empty subarray when k = 0.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
Prefix sums · subarrays summing to k
How many contiguous subarrays of 1, 2, 1, -1, 2, 1 sum to 3?
Try your own input
- k
- 3
- Prefix sum
- 0
- Looking for pre − k
- —
- Subarrays
- 0
Top row: the array. Bottom row: prefix sums. The sum of i..j is pre[j+1] − pre[i], so a sum of 3 means an earlier prefix equal to pre − 3. The empty prefix 0 counts once.
InvariantThe map holds how many times each prefix sum appeared before the current position.
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 724, with it.
Python
def count_subarrays(nums: list[int], k: int) -> int:
"""Number of non-empty subarrays whose sum is k (negatives allowed)."""
seen = {0: 1} # prefix sum -> occurrences; the empty prefix counts once
pre = ans = 0
for x in nums:
pre += x
ans += seen.get(pre - k, 0) # sum(j..i) = pre_i - pre_j
seen[pre] = seen.get(pre, 0) + 1
return ansC++
// Number of non-empty subarrays whose sum is k (negatives allowed).
int countSubarrays(const vector<int>& nums, int k) {
unordered_map<long long, int> seen{{0, 1}}; // prefix sum -> occurrences
long long pre = 0;
int ans = 0;
for (int x : nums) {
pre += x;
auto it = seen.find(pre - k); // sum(j..i) = pre_i - pre_j
if (it != seen.end()) ans += it->second;
seen[pre]++;
}
return ans;
}Java
class Solution {
// Number of non-empty subarrays whose sum is k (negatives allowed).
int countSubarrays(int[] nums, int k) {
Map<Long, Integer> seen = new HashMap<>(); // prefix sum -> occurrences
seen.put(0L, 1); // the empty prefix
long pre = 0;
int ans = 0;
for (int x : nums) {
pre += x;
ans += seen.getOrDefault(pre - k, 0); // sum(j..i) = pre_i - pre_j
seen.merge(pre, 1, Integer::sum);
}
return ans;
}
}Go
// countSubarrays returns how many non-empty subarrays sum to k (negatives allowed).
func countSubarrays(nums []int, k int) int {
seen := map[int]int{0: 1} // prefix sum -> occurrences; the empty prefix counts once
pre, ans := 0, 0
for _, x := range nums {
pre += x
ans += seen[pre-k] // sum(j..i) = pre_i - pre_j
seen[pre]++
}
return ans
}Common variants
Problems at this stop also need the 3 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
Difference array: range adds, one prefix sum at the endO(n + q) time · O(n) space
Many updates of the form add v to [l, r] with the result needed only at the end: add v at diff[l] and subtract it at diff[r + 1], O(1) each, then one prefix sum rebuilds the array. LC 1094 (Car Pooling), LC 1109 (Corporate Flight Bookings) and LC 370 (Range Addition) work this way.
Python
def range_add(n: int, updates: list[tuple[int, int, int]]) -> list[int]:
"""n zeros, then each (l, r, v) adds v to positions l..r (LC 370)."""
diff = [0] * (n + 1) # diff[i] = a[i] - a[i - 1]; the extra slot takes r + 1 = n
for l, r, v in updates:
diff[l] += v
diff[r + 1] -= v # the change stops after r
res, run = [], 0
for i in range(n):
run += diff[i] # prefix sums of the differences rebuild the array
res.append(run)
return resC++
// n zeros, then each {l, r, v} adds v to positions l..r (LC 370).
vector<long long> rangeAdd(int n, const vector<array<int, 3>>& updates) {
vector<long long> diff(n + 1, 0); // diff[i] = a[i] - a[i - 1]; the extra slot takes r + 1 = n
for (auto [l, r, v] : updates) {
diff[l] += v;
diff[r + 1] -= v; // the change stops after r
}
vector<long long> res(n);
long long run = 0;
for (int i = 0; i < n; i++) res[i] = run += diff[i]; // prefix sums rebuild the array
return res;
}Java
class Solution {
// n zeros, then each {l, r, v} adds v to positions l..r (LC 370).
long[] rangeAdd(int n, int[][] updates) {
long[] diff = new long[n + 1]; // diff[i] = a[i] - a[i - 1]; the extra slot takes r + 1 = n
for (int[] u : updates) {
diff[u[0]] += u[2];
diff[u[1] + 1] -= u[2]; // the change stops after r
}
long[] res = new long[n];
long run = 0;
for (int i = 0; i < n; i++) res[i] = run += diff[i]; // prefix sums rebuild the array
return res;
}
}Go
// rangeAdd starts from n zeros; each {l, r, v} adds v to positions l..r (LC 370).
func rangeAdd(n int, updates [][3]int) []int {
diff := make([]int, n+1) // diff[i] = a[i] - a[i-1]; the extra slot takes r + 1 = n
for _, u := range updates {
diff[u[0]] += u[2]
diff[u[1]+1] -= u[2] // the change stops after r
}
res := make([]int, n)
run := 0
for i := 0; i < n; i++ {
run += diff[i] // prefix sums of the differences rebuild the array
res[i] = run
}
return res
}2-D prefix sums: rectangle sums by inclusion-exclusionO(rows × cols) setup · O(1) per query
When a fixed matrix gets many sub-rectangle sum queries: pre[r][c] holds the sum of the top-left r × c block, with an extra zero row and column so edges need no checks, and each query is four corners by inclusion-exclusion in O(1). LC 304 (Range Sum Query 2D), LC 1314 (Matrix Block Sum); LC 1074 adds a hash map on top.
Python
class Matrix2D:
"""Sum of any sub-rectangle in O(1) after O(rows × cols) setup (LC 304)."""
def __init__(self, grid: list[list[int]]):
rows, cols = len(grid), len(grid[0])
# pre[r][c]: sum of the top-left r × c block; row 0 and column 0 stay zero
self.pre = [[0] * (cols + 1) for _ in range(rows + 1)]
for r in range(rows):
for c in range(cols):
self.pre[r + 1][c + 1] = self.pre[r][c + 1] + self.pre[r + 1][c] - self.pre[r][c] + grid[r][c]
def sum(self, r1: int, c1: int, r2: int, c2: int) -> int:
"""Corners (r1, c1) and (r2, c2), both inclusive."""
p = self.pre
return p[r2 + 1][c2 + 1] - p[r1][c2 + 1] - p[r2 + 1][c1] + p[r1][c1]C++
// Sum of any sub-rectangle in O(1) after O(rows × cols) setup (LC 304).
class Matrix2D {
vector<vector<long long>> pre; // pre[r][c]: sum of the top-left r × c block
public:
explicit Matrix2D(const vector<vector<int>>& grid) {
int rows = grid.size(), cols = grid[0].size();
pre.assign(rows + 1, vector<long long>(cols + 1, 0)); // row 0 and column 0 stay zero
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++) pre[r + 1][c + 1] = pre[r][c + 1] + pre[r + 1][c] - pre[r][c] + grid[r][c];
}
// Corners (r1, c1) and (r2, c2), both inclusive.
long long sum(int r1, int c1, int r2, int c2) const {
return pre[r2 + 1][c2 + 1] - pre[r1][c2 + 1] - pre[r2 + 1][c1] + pre[r1][c1];
}
};Java
// Sum of any sub-rectangle in O(1) after O(rows × cols) setup (LC 304).
class Matrix2D {
private final long[][] pre; // pre[r][c]: sum of the top-left r × c block
Matrix2D(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
pre = new long[rows + 1][cols + 1]; // row 0 and column 0 stay zero
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++) pre[r + 1][c + 1] = pre[r][c + 1] + pre[r + 1][c] - pre[r][c] + grid[r][c];
}
// Corners (r1, c1) and (r2, c2), both inclusive.
long sum(int r1, int c1, int r2, int c2) {
return pre[r2 + 1][c2 + 1] - pre[r1][c2 + 1] - pre[r2 + 1][c1] + pre[r1][c1];
}
}Go
// Matrix2D answers the sum of any sub-rectangle in O(1) after O(rows × cols) setup (LC 304).
type Matrix2D struct {
pre [][]int // pre[r][c]: sum of the top-left r × c block
}
func NewMatrix2D(grid [][]int) *Matrix2D {
rows, cols := len(grid), len(grid[0])
pre := make([][]int, rows+1) // row 0 and column 0 stay zero
for r := range pre {
pre[r] = make([]int, cols+1)
}
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
pre[r+1][c+1] = pre[r][c+1] + pre[r+1][c] - pre[r][c] + grid[r][c]
}
}
return &Matrix2D{pre}
}
// Sum takes corners (r1, c1) and (r2, c2), both inclusive.
func (m *Matrix2D) Sum(r1, c1, r2, c2 int) int {
p := m.pre
return p[r2+1][c2+1] - p[r1][c2+1] - p[r2+1][c1] + p[r1][c1]
}Sort by start, merge overlapsO(n log n) time · O(n) space
For the union of intervals (merging, inserting, intersecting, total covered length): sort by start, and when a new interval starts no later than the last merged one ends, extend that one to the larger end; otherwise start a new run. LC 56 (Merge Intervals), LC 57 (Insert Interval) and LC 986 (Interval List Intersections) start here.
Python
def merge(intervals: list[list[int]]) -> list[list[int]]:
"""Union of closed intervals, by start; touching ones such as [1, 2] and [2, 3] merge."""
res: list[list[int]] = []
for start, end in sorted(intervals):
if res and start <= res[-1][1]: # overlaps the last merged interval
res[-1][1] = max(res[-1][1], end)
else:
res.append([start, end])
return resC++
// Union of closed intervals, by start; touching ones such as [1, 2] and [2, 3] merge.
vector<pair<int, int>> mergeIntervals(vector<pair<int, int>> intervals) {
sort(intervals.begin(), intervals.end());
vector<pair<int, int>> res;
for (auto [start, end] : intervals) {
if (!res.empty() && start <= res.back().second) // overlaps the last merged interval
res.back().second = max(res.back().second, end);
else
res.push_back({start, end});
}
return res;
}Java
class Solution {
// Union of closed intervals, by start; touching ones such as [1, 2] and [2, 3] merge.
List<int[]> merge(int[][] intervals) {
int[][] sorted = intervals.clone();
Arrays.sort(sorted, Comparator.comparingInt(iv -> iv[0]));
List<int[]> res = new ArrayList<>();
for (int[] iv : sorted) {
int[] last = res.isEmpty() ? null : res.get(res.size() - 1);
if (last != null && iv[0] <= last[1]) last[1] = Math.max(last[1], iv[1]); // overlaps the last merged interval
else res.add(new int[] {iv[0], iv[1]});
}
return res;
}
}Go
import "sort"
// merge returns the union of closed intervals, by start; touching ones such as [1, 2] and [2, 3] merge.
func merge(intervals [][2]int) [][2]int {
sorted := append([][2]int(nil), intervals...)
sort.Slice(sorted, func(i, j int) bool { return sorted[i][0] < sorted[j][0] })
var res [][2]int
for _, iv := range sorted {
if n := len(res); n > 0 && iv[0] <= res[n-1][1] { // overlaps the last merged interval
res[n-1][1] = max(res[n-1][1], iv[1])
} else {
res = append(res, iv)
}
}
return res
}Why it works
- Because sum(l..r) = pre[r+1] − pre[l], the number of subarrays ending at r with sum k equals how many earlier prefix sums equal pre[r+1] − k. Counting prefix sums in a hash map tallies every subarray exactly once, grouped by its right end, in one pass.
- The seed {0: 1} stands for the empty prefix pre[0]; without it, subarrays starting at index 0 are missed.
- A difference array is the inverse of prefix sums: after diff[l] += v and diff[r+1] −= v, one prefix pass adds v to exactly the positions l..r.
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
子数组和可以写成两个前缀和的差,pre[r+1] − pre[l]。所以我从左往右扫,维护当前前缀和,同时用哈希表记录每个前缀和出现过几次;以当前位置结尾、和为 k 的子数组数量,就是之前前缀和等于当前值减 k 的次数。哈希表要先放入 {0: 1} 表示空前缀。这样每个子数组按右端点恰好统计一次,时间 O(n),而且对负数也成立。A subarray sum is the difference of two prefix sums, pre[r + 1] minus pre[l]. So I scan once, keep the running prefix sum, and count in a hash map how often each prefix sum has appeared; the subarrays ending here with sum k are exactly the earlier prefixes equal to the current sum minus k. I seed the map with zero seen once for the empty prefix. Every subarray is counted once at its right end, in O(n) time, and unlike a sliding window it works with negative numbers.Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
5 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
Practice by stage
This stop's 25 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Foundation 2
| # | Problem | Approach | Rating |
|---|---|---|---|
| 724 | Find Pivot Index | Compute the right-side sum from the total and the accumulated left-side sum instead of repeatedly summing ranges. | |
| 370 | Range Addition 🔒 | Represent each closed-range increment as two endpoint updates in a difference array. |
Core 20
| # | Problem | Approach | Rating |
|---|---|---|---|
| 560 | Subarray Sum Equals K | Use prefix-sum frequencies to find earlier states differing by k, supporting negative values and repeated prefixes. | |
| 525 | Contiguous Array | Replace zeros with negative ones and use the earliest matching prefix position to find the longest balanced interval. | |
| 523 | Continuous Subarray Sum | Record the first position of each remainder and use repeated remainders and their distance to enforce length at least two. | |
| 974 | Subarray Sums Divisible by K | Count pairs of equal prefix remainders and normalize remainders consistently for negative numbers. | |
| 930 | Binary Subarrays With Sum | Count target sums in a binary array using prefix frequencies, including runs of zeros without missing combinations. | |
| 1248 | Count Number of Nice Subarrays | Map parity to zero or one, then count intervals containing exactly k odd numbers. | |
| 1423 | Maximum Points You Can Obtain from Cards | Turn choices from both ends into removing a fixed-length middle window, subtracting its minimum sum from the total. | |
| 1109 | Corporate Flight Bookings | Record bulk flight-range increments in a difference array and recover the final values with one prefix scan. | |
| 1094 | Car Pooling | Accumulate boarding and drop-off events by stop, handling capacity when passengers leave before others board at the same stop. | |
| 2381 | Shifting Letters II | Apply bulk character shifts with signed differences and normalize negative cyclic shifts correctly. | |
| 56 | Merge Intervals | Sort by start position and merge overlapping intervals while retaining the furthest current endpoint. | |
| 57 | Insert Interval | In one linear scan, separate intervals before, overlapping, and after the new interval. | |
| 986 | Interval List Intersections | Intersect two sorted lists of disjoint intervals with two pointers, advancing the interval that ends first. | |
| 435 | Non-overlapping Intervals | Select intervals by finishing time to turn minimum removals into maximum retention. | |
| 452 | Minimum Number of Arrows to Burst Balloons | Place arrows at the earliest ending boundary, handling touching endpoints of closed intervals correctly. | |
| 253 | Meeting Rooms II 🔒 | Use an end-time heap or sweep line to find the minimum rooms needed for simultaneous meetings. | |
| 1288 | Remove Covered Intervals | Sort starts ascending and tied ends descending, then scan to identify covered intervals correctly. | |
| 1314 | Matrix Block Sum | Build two-dimensional prefix sums and use four-term inclusion-exclusion for rectangles clipped to the grid boundaries. | |
| 2055 | Plates Between Candles | Precompute the nearest boundary on both sides and plate prefix sums to answer interval queries in constant time. | |
| 2602 | Minimum Operations to Make All Array Elements Equal | Combine sorting, prefix sums, and a split position to separate each absolute-difference cost into left and right parts. |
Advanced 3
| # | Problem | Approach | Rating |
|---|---|---|---|
| 759 | Employee Free Time 🔒 | Merge all employees' busy intervals, then extract the finite gaps that are free for everyone. | |
| 1851 | Minimum Interval to Include Each Query | Sort queries offline, maintain a heap ordered by candidate interval length, and remove expired intervals promptly. | |
| 1074 | Number of Submatrices That Sum to Target | Fix two matrix boundaries, compress to one dimension, and reuse prefix-frequency counting for the target sum. |
OA questions on this topic 187
- Earliest Common Meeting SlotMeta
- Sliding Window AverageMeta
- Get Minimum Round Trip CostMeta
- Combine Two Vectors of Intervals (MLE)Meta
- Cart Prefix ZeroAmazon
- Consistency ScoreAmazon
- Get Total BalancedAmazon
- Get Smaller ItemsAmazon
- Find Max GreynessAmazon
- Get Min Connection CostAmazon
Core Skills
Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.