Prefix sums
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Many problems ask the same kind of question again and again: what is the total of this stretch of an array? Adding the stretch up every time is slow. A prefix sum adds the whole array up once, into a second array of running totals, and then answers any range sum with one subtraction. Watch it built for a = [3, 1, 4, 1, 5, 9], one slot at a time, and then used to answer a[2:5] = 10. The Software lessons on strings and on searching cover lists, indexes and slices, which this lesson uses throughout.
Many range sums
An array a holds 6 numbers. We want range sums: the total of a[lo:hi], the items from index lo up to, but not including, hi. Example: a[2:5] covers 4, 1, 5.
a = [3, 1, 4, 1, 5, 9] index: 0 1 2 3 4 5 range sum a[lo:hi] = a[lo] + ... + a[hi - 1] a[2:5] = 4 + 1 + 5 = 10 Python slices are half-open: lo is in, hi is out
اقرأ الدرس خطوة بخطوة
Many range sums
An array a holds 6 numbers. We want range sums: the total of a[lo:hi], the items from index lo up to, but not including, hi. Example: a[2:5] covers 4, 1, 5.
a = [3, 1, 4, 1, 5, 9] index: 0 1 2 3 4 5 range sum a[lo:hi] = a[lo] + ... + a[hi - 1] a[2:5] = 4 + 1 + 5 = 10 Python slices are half-open: lo is in, hi is outThe plain way: add them up
The plain way walks the range and adds each item: 4, then 5, then 10. That is hi − lo additions per query. With n items and q queries, it can cost about n × q additions.
def range_sum_slow(a, lo, hi): return sum(a[lo:hi]) a[2:5]: +4 → 4 +1 → 5 +5 → 10 3 additions for this query worst case: n additions per query, n·q for q queriesAdd up once, up front
Better: add up once, up front. Build a second array p, where p[i] is the sum of the first i items of a. It starts with p[0] = 0, the sum of no items at all.
p[i] = a[0] + a[1] + ... + a[i - 1] (= sum(a[:i])) p[0] = 0 the empty sum p has len(a) + 1 = 7 slots line 2: p = [0]Each slot reuses the last
Each new slot reuses the one before it: p[i + 1] = p[i] + a[i]. So p[1] = 0 + 3 = 3 and p[2] = 3 + 1 = 4. One addition per slot, never a recount.
line 4: p.append(p[-1] + x) p[-1] is the last slot so far, x is the next item p[1] = p[0] + a[0] = 0 + 3 = 3 p[2] = p[1] + a[1] = 3 + 1 = 4Build the whole prefix array
Carry on to the end: p = [0, 3, 4, 8, 9, 14, 23]. That took 6 additions for 6 items, so building p costs O(n) time. p has n + 1 slots, and the last one is the total.
p[3] = p[2] + a[2] = 4 + 4 = 8 p[4] = p[3] + a[3] = 8 + 1 = 9 p[5] = p[4] + a[4] = 9 + 5 = 14 p[6] = p[5] + a[5] = 14 + 9 = 23 prefix(a) = [0, 3, 4, 8, 9, 14, 23] p[6] = 23 = sum(a) n additions: O(n) time, n + 1 slots of memoryOne subtraction per query
Now a range sum is one subtraction: sum(a[lo:hi]) = p[hi] − p[lo]. p[5] = 3+1+4+1+5 and p[2] = 3+1. The shared 3+1 cancels, leaving 4+1+5: 14 − 4 = 10.
line 8: return p[hi] - p[lo] p[5] = 3 + 1 + 4 + 1 + 5 = 14 p[2] = 3 + 1 = 4 p[5] - p[2] = 4 + 1 + 5 = 14 - 4 = 10 two lookups and one subtraction: O(1)Why p starts with 0
The same p answers every range. The whole array: p[6] − p[0] = 23 − 0 = 23. This is why p starts with a 0: a range that starts at index 0 still needs a p[lo].
range_sum(p, 0, 6) = p[6] - p[0] = 23 - 0 = 23 range_sum(p, 3, 4) = p[4] - p[3] = 9 - 8 = 1 (just a[3]) range_sum(p, 2, 2) = p[2] - p[2] = 0 (empty range) without p[0] = 0, ranges from index 0 would need a special caseThe trade: memory for time
The trade: O(n) time and O(n) extra memory once, then O(1) per query, however long the range. q queries cost about n + q steps instead of n × q. If a changes, p must be rebuilt.
build one query q queries plain loop - O(n) O(n·q) prefix sums O(n) O(1) O(n + q) extra memory: n + 1 numbers a changes -> rebuild p (O(n))
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01What is prefix([2, 5, 1]) with the lesson's code?
p starts with 0, then each slot adds the next item to the last slot: 0, 0 + 2 = 2, 2 + 5 = 7, 7 + 1 = 8. p has one more slot than a.
02With p = [0, 3, 4, 8, 9, 14, 23] for a = [3, 1, 4, 1, 5, 9], what is the sum of a[1:4]?
p[4] − p[1] = 9 − 3 = 6. Check: a[1:4] holds 1, 4 and 1, and 1 + 4 + 1 = 6.
03Why does the prefix array start with p[0] = 0?
p[i] is the sum of the first i items, and the sum of no items is 0. With it, sum(a[0:hi]) = p[hi] − p[0] needs no special case.
04An array has n numbers and you must answer q range-sum queries. Roughly how many steps do prefix sums take in total?
Building p takes n additions once. Each query is then one subtraction, so q queries add about q more steps. The plain loop can need up to n additions per query, about n × q.
05After building p, you change a[2] from 4 to 7. What happens?
a[2] is part of every prefix that reaches past it: p[3] to p[6]. Each is off by 3. Rebuilding costs O(n), which is why data that changes often uses other structures.
المسرد
- Range sum
- The total of the items in one stretch of an array, such as a[lo:hi].
- a[lo:hi]
- A Python slice: the items with index lo up to, but not including, hi. It holds hi − lo items.
- Prefix
- The start of a sequence: the first i items. The empty prefix has no items.
- Prefix array (p)
- An array where p[i] is the sum of the first i items of a. It has len(a) + 1 slots and p[0] = 0.
- Running total
- A sum kept up to date as you walk through items, one addition per item. Also called a cumulative sum.
- Query
- One question asked of the data, here: what is the sum of a[lo:hi]?
- Preprocessing
- Work done once, up front, so that later queries are fast. Building p is the preprocessing here.
- O(1)
- Constant time: the cost does not grow with the input. A prefix-sum query is O(1) however long the range.
الملاحظات والمصادر
- a[lo:hi] follows Python slicing: it holds the items with index k where lo ≤ k < hi, so a[2:5] is a[2], a[3] and a[4]. That half-open rule is what makes p[hi] − p[lo] come out exactly right, with no ± 1.
- Python can build the same array for you: list(itertools.accumulate(a, initial=0)) returns [0, 3, 4, 8, 9, 14, 23]. The initial argument was added in Python 3.8.
- The costs assume what MIT 6.006 states for Python lists: reading p[i] takes constant time, and append takes constant time on average (amortised), so the build is O(n).
- If a changes often, rebuilding p after every change costs O(n). The special-topics lesson "Segment trees and Fenwick trees" covers structures that handle both changes and range sums in O(log n).
- The same running-total step appears inside counting sort (CLRS §8.2) and in key-indexed counting (Sedgewick and Wayne, LSD.java: "compute cumulates"). It also works in 2D, as a summed-area table.
- Python Standard Library: Common Sequence Operations (slices, note 4)
- Python Standard Library: itertools.accumulate
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 2: Data Structures
- Sedgewick and Wayne, Algorithms 4th ed., LSD.java (key-indexed counting: compute cumulates)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §8.2 Counting sort
- Prefix sum (overview, summed-area tables)
اختبار يتاح بعد الخطوة الأخيرة.