Question presented to candidate: "What is the prefix sum technique? Explain it, then write Python code that preprocesses a list so that any range-sum query takes constant time."
What a strong answer should cover:
- Definition:
prefix[i]is the sum of the firstielements; with a leading 0, the rangel..risprefix[r + 1] - prefix[l]. - Cost: O(n) to build, O(1) per query; O(n + q) instead of O(nยทq) for q queries.
- When to use it (static array, subarray-sum problems) and when not (frequent updates: Fenwick or segment tree).
- Extensions: 2D prefix sums with inclusion-exclusion; difference arrays for range updates.
- Python specifics:
itertools.accumulate(withinitial=0), list comprehensions for 2D tables, ints never overflow.
Code / implementation expected: Yes โ build and query functions in Python.