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
UnverifiedIdea. 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.
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
Immutable prefix sums: sumRange = prefix[r+1] − prefix[l]. Mutable cousin is Fenwick (LC 307).
Reflection
- An immutable array and many queries are prefix sums.
sum(l..r) = pref[r + 1] - pref[l]. Why seedpref[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?