Skip to content
DSA Patterns
Menu
Language
Prefix SumLC #3031 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Range Sum Query. Immutable

Problem (restated)

Design a structure that, given immutable nums, answers sumRange(left, right) efficiently.

Intuition

Precompute prefix[i] = sum of first i elements; range = prefix[r+1]-prefix[l].

Approaches

Prefix sums

Unverified
Time O(1) query / O(n) buildSpace O(n)

Idea. Build prefix once; each query is two array lookups.

Walkthrough. nums=[-2,0,3,-5,2,-1]; sumRange(0,2)=1; sumRange(2,5)=-1.

Trade-offs. Segment tree overkill for immutable + range-sum only.

Solution
export class NumArray {
  private pref: number[];
  constructor(nums: number[]) {
    this.pref = new Array(nums.length + 1).fill(0);
    for (let i = 0; i < nums.length; i++) this.pref[i + 1] = this.pref[i]! + nums[i]!;
  }
  sumRange(left: number, right: number): number {
    return this.pref[right + 1]! - this.pref[left]!;
  }
}
export class NumArray {
  private pref: number[];
  constructor(nums: number[]) {
    this.pref = new Array(nums.length + 1).fill(0);
    for (let i = 0; i < nums.length; i++) this.pref[i + 1] = this.pref[i]! + nums[i]!;
  }
  sumRange(left: number, right: number): number {
    return this.pref[right + 1]! - this.pref[left]!;
  }
}

Template connection

prefix[0] is 0 and prefix[i + 1] is prefix[i] + nums[i]. A range is prefix[right + 1] - prefix[left]. The build is O(n) and each query is O(1). The array never changes after the build.

Reflection

  • An immutable array and many queries are prefix sums. sum(l..r) = pref[r + 1] - pref[l]. Why seed pref[0] = 0?
  • The inclusive right end is the off-by-one: read pref[right + 1].
  • If the array were mutable (LC 307), why would you switch to a Fenwick tree or a segment tree?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Immutable nums. Build prefix once, then answer range sums in O(1).

-2
0
0
1
3
2
-5
3
2
4
-1
5

pref[0] = 0

Key:CurrentActive rangeMatchSettled