Beyond Big O

Range sum queries

Range sum queries

Easy

Solution guide

Reveal solution guide — spoilers

Approach

  1. Build a prefix array of length n + 1 with prefix[0] = 0 and prefix[i + 1] = prefix[i] + values[i].
  2. For each query [start, end], append prefix[end] - prefix[start] to the result in query order.
  3. Use the supplied half-open boundaries directly. Do not decrement end or rescan each range, and leave values and queries unchanged.

Why it works

prefix[end] totals exactly the values before end. Subtracting prefix[start] removes the values before start, leaving precisely indices start through end - 1. The leading zero makes ranges starting at zero and empty ranges obey the same formula.

Complexity

O(n + q) total time for n values and q queries, with O(n) auxiliary prefix storage excluding the O(q) returned sums. Use an integer type covering the stated sum bounds.

Edge cases to check

  • A query with start equal to end sums to zero, including [n, n].
  • end may equal len(values), which is a valid prefix index.
  • No queries produces an empty result; empty values permit only empty ranges. Negative values require no special-case adjustment.
Editor options
Typing preferences

Saved in this browser.

Restoring local drafts…