Dynamic Programming21 sections · 916 units
Open in Course

Building the Prefix Array

One pass

Building the prefix array takes one pass through the original array: pref[0]=0pref[0] = 0 pref[i]=pref[i1]+a[i]pref[i] = pref[i-1] + a[i] for ii from 11 to nn Each element adds to the running total. Time: O(n)O(n). Space: O(n)O(n) for the prefix array. You do this once, before any queries arrive.

After that, every query becomes fast. The preprocessing cost is fixed; the per-query cost drops dramatically.