The prefix sum trick
Tap to start →
prefix starts with 0, then adds each number.
prefix[R + 1] − prefix[L]. One subtraction.
arr = 2, 4, 1, 3, 5 → 10 − 2 = 8.
O(n) to build, then every question is O(1).
Forgetting the +1: prefix[R] − prefix[L] leaves out the last number.
Tap an answer. The full video explains why.
Free DSA in Java course. Subscribe to Compiled Canvas on YouTube.