Unit 8 of 8 · about 4 hours · implement

Prefix sums, difference arrays and prefix plus hash

Precomputation trades linear space for constant queries, and the prefix-plus-hash reduction is the template for turning a range condition into a lookup across counting problems.

You'll be able to

  • Build prefix and difference arrays and answer range queries in .
  • Reduce subarray counting to prefix-frequency lookup with the seed-first rule.
  • Choose windows versus prefix-plus-hash from the sign of the numbers.

Covers

Prefix sums, difference arrays and prefix plus hash
1

Read

In this order, only the parts listed

0 of 2 done

  1. Prefix sums and difference arraysDSA Handbook - Foundations and linear patterns

    The pattern (build once, query in ); Worked example LC 303; What it costs (1D and 2D builds and queries, difference-array updates); 2D prefix sums: inclusion-exclusion on four corners; Difference arrays: the inverse direction

  2. The prefix-sum + hash-map comboDSA Handbook - Foundations and linear patterns

    Why sliding window fails on negatives, in one trace ([1, -1, 1, 1]); The reduction (); The pattern with the {0: 1} seed; Worked example LC 560 on [1, 1, 1] with ; When the pattern bends (modulo LC 974, first-seen LC 525)

2

Focus on

  • The prefix array has entries with : a range sum is , with no special case.
  • Counting needs the seed {0: 1}: subarrays starting at index 0 would otherwise be missed.
  • Difference arrays mark at and at ; one prefix pass materializes the array, and a second prefix over it answers queries.
  • Python's % already normalizes negatives for positive ; the ((x%k)+k)%k form is for C++ and Java ports.
Common mistakes · 3
  • Off-by-one: has entries and the query is .
  • Missing seed {0: 1}: every valid prefix starting at index 0 vanishes.
  • Using a window on possibly-negative inputs; reach for prefix-plus-hash instead.
3

Try it yourself

Closed-book, before checking anything

By hand on [1, 1, 1] with : seed {0: 1}; running prefixes 1, 2, 3 need -1, 0, 1 with counts 0, 1, 1, totaling 2. Then implement range-add via difference marks plus range-sum queries, differential-tested against naive loops ( up to 20, up to 10 updates, derandomize) in Python 3.13: expect 1 passed.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Derive the 2D range-sum formula.Answer

    : subtract the top and left rectangles, add back the doubly-subtracted corner.

  2. 2.Why does the difference marking work?Answer

    Telescoping: position x accumulates all marks at indices up to x, exactly the updates covering x. A second prefix over the materialized array answers sums.

  3. 3.Where does the {0: 1} seed enter the LC 560 trace?Answer

    Prefix 2 needs 0, which never appears as a running total. The seed supplies its count of 1.

  4. 4.Modulo keys with negative running sums in Python?Answer

    key = running % k works directly since Python floors to non-negative for positive . Ports to C++ or Java need the double-mod form.

5

Practice

  • LeetCode 303: Range Sum Query - Immutable

    Build the prefix once and answer each sumRange in . Judge with the Example array [-2, 0, 3, -5, 2, -1].

    After submitting, compare against the handbook prefix-sums worked example LC 303.

  • LeetCode 560: Subarray Sum Equals K

    Implement the prefix-frequency reduction with the {0: 1} seed. Judge with the Examples [1, 1, 1] giving 2, and [1, 2, 3] giving 2.

    After submitting, compare your trace against the handbook prefix-sum-hash worked example on [1, 1, 1].

You're done when

Both are accepted, your hand trace totals 2, and you can state the window-versus-prefix choice rule from the sign of the input.

Only when you can do this without notes.

Leads to

Notes

Resources · 1 for this unit, 7 more in the section
  • DSA Handbook - Foundations and linear patternsHandbook Academy · primary

    Study Part 0, Part 1, Part 3 and Part 4 in order, plus the Part 5 Linked-list fundamentals chapter. Use the routing-rule pages for arrays versus lists, map choice, stack versus queue, two pointers, sliding windows and prefix methods before seeing solved code.

Also in this section

  • AlgoMaster DSA - linear structures sliceAlgoMaster · required

    Attempt Design HashMap, Longest Substring Without Repeating Characters and Sliding Window Maximum cold. Hide tags, state the invariant first, and add randomized operation histories to Design HashMap.

  • MIT 6.042J - asymptotics and invariantsMIT OpenCourseWare · support

    Use the asymptotics, state-machine invariants and proof-method readings when a cost or correctness argument is weak. Solve only the matching problems.

  • Algorithms lecture notes - amortized analysis and hashingJeff Erickson · support

    Use note 9 Amortized Analysis for the summation, taxation, charging and potential-function proofs, and note 5 Hashing for chaining, universal hashing and open-addressing analysis, when the handbook treatment is too brief for a proof.

  • Algorithmica - memory and data layoutSergey Slotin · support

    Read the memory hierarchy, cache and complexity-model chapters, then measure one contiguous-versus-linked and one hash-versus-ordered workload crossover.

  • NeetCode - unseen linear problemsNeetCode · optional

    Use only for two tag-hidden transfer problems after the AlgoMaster slice. Do not start another full roadmap or watch a solution before the attempt is complete.

  • Hypothesis documentation - Quickstart and stateful testingHypothesis · support

    Follow Quickstart for @given strategies and the pytest combination, Configuring test settings for max_examples and derandomize, then Rule-based state machines (rule, precondition, invariant, run_state_machine_as_test) for randomized operation histories against dict and deque oracles.

  • CPython source - list and dict objectsPython Software Foundation · reference

    Read list_resize in Objects/listobject.c for the growth formula and pattern comment, and the USABLE_FRACTION definition, perturbation-probing comment and dummy-entry handling in Objects/dictobject.c. Read the cited functions and comments only.