awelgorithms

Prefix at i is the sum of a[0..i)

Updated

Exclusive-end prefix: P[i] is a[0] + … + a[i-1]. P[0] is the empty sum 0. P has length n+1. P[n] is the total. P[i] does not include a[i].

What to focus on

Fill with P[i+1] ← P[i] + a[i]. Reading P[i] as “sum through index i” is the off-by-one for this layout.

Worked examples

three cells

a = [4, 1, 9]
  1. P[0] ← 0
  2. P[1] ← 0+4 = 4
  3. P[2] ← 4+1 = 5
  4. P[3] ← 5+9 = 14

Result: P = [0, 4, 5, 14]

one cell

a = [7]
  1. P[0] ← 0
  2. P[1] ← 7

Result: P = [0, 7]

empty

a = []
  1. n = 0
  2. only the empty sum
  3. P[0] ← 0

Result: P = [0]

Try it

Write exclusivePrefix(a). a is the input array, and may be empty. Exclusive prefix P[i] is the sum of a[0] through a[i-1]. P has length n+1. P[i] covers a[0..i). Return P. [4, 1, 9] → [0, 4, 5, 14] [7] → [0, 7] [] → [0]

a is an array of integers and may be empty. Exclusive layout: P has length n+1, P[0] is 0, and P[i] covers a[0..i).