COMPILED CANVAS
DSA IN JAVA

Any range sum in ONE step

The prefix sum trick

Tap to start →

BUILD

Running totals

02671015

prefix starts with 0, then adds each number.

1 of 4 · keep tapping →
FORMULA

Sum from L to R

prefix[R+1] − prefix[L]

prefix[R + 1] − prefix[L]. One subtraction.

2 of 4 · keep tapping →
EXAMPLE

Index 1 to 3

24135

arr = 2, 4, 1, 3, 5 → 10 − 2 = 8.

3 of 4 · keep tapping →
WHY

Build once, ask forever

Loop each time
Prefix sum

O(n) to build, then every question is O(1).

4 of 4 · keep tapping →
⚠ MOST PEOPLE MISS THIS

The mistake

Forgetting the +1: prefix[R] − prefix[L] leaves out the last number.

QUICK QUIZ

Can you get it?

Tap an answer. The full video explains why.

📸 SCREENSHOT THIS

Cheat sheet

  • prefix is 1 box longer
  • Starts with 0
  • Build: O(n)
  • Range sum: prefix[R+1] − prefix[L]
  • Big numbers → long
COMPILED CANVAS

Want the full lesson?

▶ Watch the full videoPractice + free notes

Free DSA in Java course. Subscribe to Compiled Canvas on YouTube.

Watch the full video