#303

Range Sum Query - Immutable

Easy Prefix array

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Design a class that answers many queries "sum of nums from index left to right" on a fixed array.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: answer "sum from left to right" many times on the same array.

Why this works: build the prefix totals once; every query is then a subtraction.

Example: nums = [-2, 0, 3, -5, 2, -1]

prefix = [0, -2, -2, 1, -4, -2, -3]sum(0..2) = prefix[3] - prefix[0] = 1sum(2..5) = prefix[6] - prefix[2] = -1

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using a prefix array of size n and then special-casing left = 0. The extra leading 0 removes the edge case.