awelgorithms

Count prefixes with a given remainder

Updated

p[i]%k is the remainder of the prefix ending at i. Count how many prefixes land on remainder r. Same remainder later is the subarray-sum-multiple-of-k trick.

What to focus on

Inclusive p on a=[4,1,9]: 4,5,14. Mod 3: 1,2,2. Empty prefix remainder 0 is a separate policy — this skill counts the n inclusive prefixes unless named.

Worked examples

r=2

a = [4, 1, 9], k = 3, r = 2, p = [4, 5, 14]
  1. 4%3=1
  2. 5%3=2
  3. 14%3=2

Result: 2 prefixes (i=1 and i=2)

r=1

a = [4, 1, 9], k = 3, r = 1, p = [4, 5, 14]
  1. only 4%3=1

Result: 1 prefix (i=0)

r=0 none

a = [4, 1, 9], k = 3, r = 0, p = [4, 5, 14]
  1. no inclusive p divisible by 3
  2. empty p=0 would count if you include it

Result: 0 inclusive prefixes

Try it

Write countRemainder(a, k, r). a is the input array. k is the modulus. r is the remainder to count. Inclusive p[i] covers a[0..i]. Return how many inclusive prefixes have p[i] % k == r. [4, 1, 9] k=3 r=2 → 2 [4, 1, 9] k=3 r=1 → 1 [4, 1, 9] k=3 r=0 → 0 inclusive prefixes

a is a non-empty array of integers. k is a positive integer. r is in 0..k-1. Inclusive p has length n. p[i] covers a[0..i].