cswork / templatesOpen the Line 500 list

STOP 05 · LINEAR STRUCTURES

Prefix Sums and Intervals

Prefix sums with a hash count O(n) time · O(n) space

Contest ratings Rating 1375–Rating 2286· median Rating 1624(15 of 25 problems rated by zerotrac)

Open the Line 500 list · stop 05 · 25 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 14 companies · in 26 reportsMeta 7, TikTok / ByteDance 5, Amazon 2, OpenAI 2, Adobe 1

Warm up with this one

LC 724Find Pivot IndexEasy
Stuck? 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

  1. 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.
  2. When counting subarrays that sum to k, seed the map with {0: 1} for subarrays that start at index 0.
  3. 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.

Interactive demo · step by 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
10
21
12
-13
24
15
·pre[1]
·pre[2]
·pre[3]
·pre[4]
·pre[5]
·pre[6]
CurrentDiscovered / computedAnswer
Map (prefix sum×count)
0×1
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 ans
C++
// 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 res
C++
// 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 res
C++
// 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

  1. 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.
  2. The seed {0: 1} stands for the empty prefix pre[0]; without it, subarrays starting at index 0 are missed.
  3. 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),而且对负数也成立。
English
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.

Key points you covered (0 of 3)
How well did you know it?

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

5 questions
  1. Prefix sums are P[0] = 0 and P[i] = a[0] + … + a[i-1]. The sum of a[l..r], both ends included, is:
  2. What is the standard way to merge a list of possibly overlapping intervals, and its time?
  3. An array of length n gets q updates "add v to every element of a[l..r]" and is read once at the end. With a difference array, the total time is:
  4. a has length n and queries holds q (l, r) ranges. What is the time complexity?
    def range_sums(a, queries):
        p = [0]
        for x in a:
            p.append(p[-1] + x)
        return [p[r + 1] - p[l] for l, r in queries]
  5. a has length n and queries holds q (l, r) ranges. What is the worst-case time complexity?
    def range_sums(a, queries):
        return [sum(a[l:r + 1]) for l, r in queries]

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

#ProblemApproachRating
724Find Pivot IndexCompute the right-side sum from the total and the accumulated left-side sum instead of repeatedly summing ranges.
370Range Addition 🔒Represent each closed-range increment as two endpoint updates in a difference array.

Core 20

#ProblemApproachRating
560Subarray Sum Equals KUse prefix-sum frequencies to find earlier states differing by k, supporting negative values and repeated prefixes.
525Contiguous ArrayReplace zeros with negative ones and use the earliest matching prefix position to find the longest balanced interval.
523Continuous Subarray SumRecord the first position of each remainder and use repeated remainders and their distance to enforce length at least two.
974Subarray Sums Divisible by KCount pairs of equal prefix remainders and normalize remainders consistently for negative numbers.Rating 1676
930Binary Subarrays With SumCount target sums in a binary array using prefix frequencies, including runs of zeros without missing combinations.Rating 1592
1248Count Number of Nice SubarraysMap parity to zero or one, then count intervals containing exactly k odd numbers.Rating 1624
1423Maximum Points You Can Obtain from CardsTurn choices from both ends into removing a fixed-length middle window, subtracting its minimum sum from the total.Rating 1574
1109Corporate Flight BookingsRecord bulk flight-range increments in a difference array and recover the final values with one prefix scan.Rating 1570
1094Car PoolingAccumulate boarding and drop-off events by stop, handling capacity when passengers leave before others board at the same stop.Rating 1441
2381Shifting Letters IIApply bulk character shifts with signed differences and normalize negative cyclic shifts correctly.Rating 1793
56Merge IntervalsSort by start position and merge overlapping intervals while retaining the furthest current endpoint.
57Insert IntervalIn one linear scan, separate intervals before, overlapping, and after the new interval.
986Interval List IntersectionsIntersect two sorted lists of disjoint intervals with two pointers, advancing the interval that ends first.Rating 1542
435Non-overlapping IntervalsSelect intervals by finishing time to turn minimum removals into maximum retention.
452Minimum Number of Arrows to Burst BalloonsPlace arrows at the earliest ending boundary, handling touching endpoints of closed intervals correctly.
253Meeting Rooms II 🔒Use an end-time heap or sweep line to find the minimum rooms needed for simultaneous meetings.
1288Remove Covered IntervalsSort starts ascending and tied ends descending, then scan to identify covered intervals correctly.Rating 1375
1314Matrix Block SumBuild two-dimensional prefix sums and use four-term inclusion-exclusion for rectangles clipped to the grid boundaries.Rating 1484
2055Plates Between CandlesPrecompute the nearest boundary on both sides and plate prefix sums to answer interval queries in constant time.Rating 1819
2602Minimum Operations to Make All Array Elements EqualCombine sorting, prefix sums, and a split position to separate each absolute-difference cost into left and right parts.Rating 1903

Advanced 3

#ProblemApproachRating
759Employee Free Time 🔒Merge all employees' busy intervals, then extract the finite gaps that are free for everyone.Rating 1710
1851Minimum Interval to Include Each QuerySort queries offline, maintain a heap ordered by candidate interval length, and remove expired intervals promptly.Rating 2286
1074Number of Submatrices That Sum to TargetFix two matrix boundaries, compress to one dimension, and reuse prefix-frequency counting for the target sum.Rating 2189

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.