awelgorithms

Prefix counts of a predicate

Updated

Inclusive count prefix: C[i] is how many indices in 0..i match pred. C[i] ← C[i-1] + (pred(a[i]) ? 1 : 0), with C[-1]=0. Range count [L, R] is C[R] − C[L-1].

What to focus on

This is range counting after one pass. Odds and “equals 1” are the usual preds. C[i] is a count, not a sum of values.

Worked examples

odds

a = [4, 1, 9]
  1. 4 even → C[0]=0
  2. 1 odd → C[1]=1
  3. 9 odd → C[2]=2

Result: C = [0, 1, 2]

odd range

a = [4, 1, 9], odds on [1, 2]
  1. C[2]-C[0] = 2-0 = 2

Result: indices 1 and 2 match

count of 1s

a = [4, 1, 9, 1]
  1. C = [0, 1, 1, 2]
  2. ones on [1, 3] = C[3]-C[0] = 2

Result: 2

Try it

Write prefixCount(a, pred). a is the input array. pred(x) returns true or false for each value x. Return the count table C. C[i] is how many matches sit in a[0..i]. Odds on [4, 1, 9] → C = [0, 1, 2] Odds on [1, 2] → C = [1, 1] Count of 1s on [4, 1, 9, 1] → C = [0, 1, 1, 2]

a is a non-empty array of integers. pred returns true or false on every a[i]. 0 ≤ L ≤ R < n.