Optimization challengeIntermediate

Recomputing range sums per query

Scenario

An analytics endpoint answers q = 10⁵ queries of the form "sum of values[l..r]" over an array of n = 10⁵ daily totals. It is too slow. Then a second requirement lands: values can also be updated between queries. Optimize both versions.

Broken
1def range_sums(values, queries):
2 out = []
3 for l, r in queries:
4 out.append(sum(values[l:r + 1]))
5 return out

The corrected version appears here once you have revealed everything below.

Your task

  1. State the current worst-case cost and what structure of the work is repeated across queries.
  2. Give an O(n) preprocessing / O(1) per query solution for the read-only case.
  3. Explain why that solution breaks when a single value is updated, and what the cost of maintaining it would be.
  4. Propose a structure that supports both point updates and range sums in O(log n) and sketch its operations.
  5. Discuss when a plain prefix array is still the right choice despite updates.
OptimizationComplexity AnalysisPattern Recognition

Work it out

Write your analysis before revealing anything. The self-check below compares it against what a strong answer contains.

Reveal

Progressive — each section builds on the previous one.

The bottleneck
Key observation
The fix
Edge cases
Complexity
What this tests

Self-check

Tick what your analysis covered. Be honest — this feeds your readiness profile.

0/7

Related concepts