NeetCode #53LC-303EasyArrays & Hashing
← Back to All Problems#53 · #303 · Range Sum Query - Immutable(区域和检索 - 数组不可变)
📌 Problem Statement & Constraints
Design a class that answers sum queries on an immutable array. Implement
NumArray(nums) and sumRange(left, right), returning the sum of nums[left..right] inclusive. Constraints: 1 <= nums.length <= 10^4, up to 10^4 queries.💡 Core Algorithmic Approaches
- Recomputing the sum per query is O(n), which is too slow for 10^4 queries over a 10^4 array.
- Precompute a prefix-sum array
Pof lengthn + 1, whereP[i]is the sum of the firstielements andP[0] = 0. - Then
sumRange(l, r) = P[r + 1] - P[l], in O(1). - The leading zero is what makes the formula work uniformly for
l == 0without a special case.
💻 Benchmark Python3 Implementation
class NumArray:
def __init__(self, nums: List[int]):
# P[i] = sum of nums[0..i-1]; the leading 0 removes boundary cases
self.P = [0] * (len(nums) + 1)
for i, x in enumerate(nums):
self.P[i + 1] = self.P[i] + x
def sumRange(self, left: int, right: int) -> int:
return self.P[right + 1] - self.P[left]⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n) to build, then O(1) per query. The brute-force alternative is O(n) per query.
💾 Space Complexity
O(n) for the prefix array.
⚠️ Interview Pitfalls & Follow-ups
- Indexing the prefix array as
P[right] - P[left]: off by one; the correct form usesP[right + 1]. - Omitting the leading zero: then
left == 0requires a branch, and negative indices silently produce wrong answers in Python. - Summing lazily and caching: works, but the immutable guarantee is exactly what makes the one-shot prefix build the right choice.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
区域和检索 - 数组不可变
给定一个整数数组 nums,处理以下类型的多个查询:计算索引 left 到 right(包含 left 和 right)之间的 nums 元素的和。实现 NumArray 类: __init__(nums) 初始化; sumRange(left, right) 返回该区间的元素和。约束:1 ≤ nums.length ≤ 10^4;-10^5 ≤ nums[i] ≤ 10^5;0 ≤ left ≤ right < nums.length;最多调用 10^4 次 sumRange。
核心要点
- 一维前缀和(标准解) :构造 prefix ,其中 prefix[i] 表示 nums[0..i-1] 的和,因此 prefix[0] = 0 ,长度为 n + 1。
- 查询公式 : sumRange(left, right) = prefix[right + 1] - prefix[left] 。
- 为什么 prefix 要多一位 : prefix[0] = 0 使得 left == 0 时无需特判,直接相减即可。
- 权衡 :预处理 O(n),单次查询 O(1)。相比暴力每次 O(right − left + 1),在查询次数多时优势明显。
常见陷阱
- 前缀和数组少开一位 :若用长度 n 的数组( prefix[i] 表示 nums[0..i] 的和),查询公式变成 prefix[right] - prefix[left-1] ,需要为 left == 0 特判。多开一位是更简洁的做法。
- 查询公式写成 prefix[right] - prefix[left] :这样会把 nums[right] 漏掉,必须用 prefix[right + 1] 。
- 每次查询都 sum(nums[left:right+1]) :切片加求和是 O(n),在 10^4 次查询下会超时。
参考实现
class NumArray:
def __init__(self, nums: list[int]):
# prefix[i] = nums[0..i-1] 的和;prefix[0] = 0 便于处理 left == 0
self.prefix = [0]
for x in nums:
self.prefix.append(self.prefix[-1] + x)
def sumRange(self, left: int, right: int) -> int:
return self.prefix[right + 1] - self.prefix[left]