You have an array of numbers and two things to do over and over: change one value, and ask for the sum of a range. Sounds trivial — and with a plain array you can always do one of them instantly. The trouble is the other one.
Keep the raw array and an update is one write, but a range sum means walking every element in the range: slow when the array is huge and the ranges are wide. Keep a table of prefix sums instead and any range sum is a single subtraction — but now changing one value forces you to rebuild half the table.
That tension between fast reads and fast writes is the whole story. Segment trees and Fenwick trees (also called binary indexed trees) escape it: they answer both a point update and a range query in — a handful of steps even for millions of elements.
Comments
Loading comments...