Practice Discrete Math

Algorithms / Prefix Sums

Least You Need to Know: Prefix Sums, Range Aggregates, and Subtracting History

Prefix sums precompute cumulative totals so a range sum becomes **one subtraction of two histories**. This is one of the highest-leverage preprocessing tricks in algorithmic problem solving.

جو کم از کم جاننا ضروری ہے

اہم علامتیں

pref[i] sum of elements up to index i
range(l, r) aggregate over a contiguous interval
pref[r] - pref[l-1] range-sum query by subtraction

مختصر حل شدہ مثال

  • For array `[2, 5, 1, 4]`, the prefix sums are `[2, 7, 8, 12]`.
  • The range sum from index `2` to `4` is `12 - 2 = 10`.
  • Instead of re-adding the interval each time, reuse the cumulative totals.
  • That is the main speedup provided by prefix sums.

عام غلطیاں

اس قسم کے سوال کو کیسے پہچانیں

Next recommended lesson

Continue through this topic with Least You Need to Know: Priority Queues, Scheduling, and Lazy Updates.

Least You Need to Know: Priority Queues, Scheduling, and Lazy Updates

Related lessons

Keep going with nearby lessons in the same topic.

More ways to explore

مشق شروع کریں