Python coding

Sums of many ranges

Given a list of integers nums and a list queries, where each query is a pair [lo, hi] with 0 <= lo <= hi < len(nums), return a list with the sum of nums[lo] through nums[hi] (both ends included) for each query, in the order given.

There can be far more queries than numbers: after one pass over nums, each query should take O(1). Values may be negative and queries may be empty.

Besides the tests, one large input (8,000 queries over 3,000 numbers) with a ~300 ms limit (scaled to your device's speed): brute force won't pass.

  • range_sums([3,1,4,1,5], [[0,2],[1,3],[4,4]]) → [8,6,5]
  • range_sums([2,-7,5,-1], [[0,3],[1,1],[2,3]]) → [-1,-7,4]
  • range_sums([10], [[0,0],[0,0]]) → [10,10]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Summing each range from scratch costs O(n) per query. Precompute something once so that every range becomes arithmetic on two stored values.

Hint 2

Let prefix[i] be the sum of the first i numbers, with prefix[0] = 0. Then the sum from lo to hi is prefix[hi + 1] - prefix[lo].

Hint 3

The trap is the off-by-one: without the leading 0, a range that starts at index 0 needs a special case, and in Python prefix[-1] silently reads the last total.

Solution and why it works
pythonO(n + q), q = number of queries · O(n)
def range_sums(nums: list[int], queries: list[list[int]]) -> list[int]:
    prefix = [0]                         # prefix[i] = sum of the first i numbers
    for x in nums:
        prefix.append(prefix[-1] + x)
    return [prefix[hi + 1] - prefix[lo] for lo, hi in queries]

prefix[i] holds the sum of the first i numbers, so any range is the difference of two prefixes: prefix[hi + 1] - prefix[lo]. Building it is one O(n) pass and every query is O(1), instead of O(n) each. The leading 0 is what keeps the formula uniform: without it, ranges that start at index 0 need a special case, and in Python prefix[lo - 1] with lo = 0 quietly reads the last element instead of failing.