~/problems / Arrays & hashing / Prefix sums and difference arrays

Basics: range sums with a prefix array

easy basics ~10 min

Write range_sums(nums: list[int], queries: list[tuple[int, int]]) -> list[int].

Each query (l, r) asks for nums[l] + nums[l + 1] + ... + nums[r] (both ends inclusive). Return the answers in query order.

range_sums([3, -1, 4, 1, 5], [(0, 4), (1, 3), (2, 2)])   # [12, 4, 4]
range_sums([7], [(0, 0), (0, 0)])                        # [7, 7]

Constraints: 0 <= l <= r < len(nums), up to 10^5 numbers and 10^5 queries, values may be negative. Summing each slice separately is O(n) per query and too slow for the large test.

Show hint

build P with P[0] = 0 and P[i + 1] = P[i] + nums[i]; then the sum of nums[l..r] is P[r + 1] - P[l].

Topic: Prefix sums and difference arrays. O(1) range sums (1D and 2D); O(1) range updates with difference arrays.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc