Dynamic Programming21 sections · 915 units
Open in Course

The Range Sum Problem

Why we need this

Here's the setup: you have an array aa of nn integers. You receive qq queries, each asking for the sum of elements from index ll to index rr.

For one query, you'd write a loop: start at ll, add elements until rr, return the sum. That's O(r−l+1)O(r - l + 1) per query, which in the worst case is O(n)O(n). Multiply by qq queries and you get O(n⋅q)O(n \cdot q). When both nn and qq are large, this is too slow. You need a smarter approach.