TRT
Sign in
easyAdvancedLeetCode#prefix sums

Range sum query: immutable

Answer many range-sum queries on a fixed array in O(1) each with a prefix-sum array.

The Runtime Theory Team1 min read
Taught inPrefix sumsPro — members onlyStore the running total at every position once, and the sum of any range becomes one subtraction. Combined with a hash map, prefix sums count subarrays with a given sum, even with negative numbers.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inStandard benchmark input 1 (valid boundary constraints)

outOptimal target output verified in O(N) / O(N log N) time

inEdge case input 2 (minimum size / duplicate values / skewed distribution)

outHandles degenerate boundary without off-by-one or overflow

Given an array, implement sumRange(left, right), which returns the sum of the elements from left to right inclusive. It will be called many times.

Before you code

Summing on every call is O(n). Build the prefix sums once in the constructor.

Hints

  1. P has length n + 1 with P[0] = 0.
  2. sumRange(l, r) = P[r + 1] - P[l].

Production & complexity notes

When solving Range sum query: immutable on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Prefix sums to reinforce the underlying pattern.

What it practices

The prefix-sum array and its off-by-one convention, from Prefix sums.

Not started

Sign in to save your learning progress.

Sign in to save