Proofs: Prefix sum hash counting
These are the human proofs of Prefix sum hash counting, at full length.
Prefix sum hash counting counts the subarrays with sum k full
This proof shows: correctness.
We use the pseudocode of the page on and a target . Let and for , so that the subarray has sum . Treat the hash table as a map from values to counts, where an absent key has count . For let be the number of pairs with and .
Claim. At the start of step (and, for , when the loop ends):
- ;
- for every value , ;
- .
Proof. By induction on .
Base, . Line L1 sets , and every other count to , which matches the one value , and , because there is no pair with .
Step. Assume the claim at the start of step . Line L3 sets . The pairs counted by but not by are those with , that is, the starts with and . By part 2, line L4 adds exactly their number, , so . Line L5 then adds one to , so part 2 holds with in place of .
Theorem. COUNT-SUM-K returns the number of subarrays of with sum .
Proof. By the claim with , line L6 returns , the number of pairs with . The loop runs times with one lookup and one update of , so the algorithm stops.
Remark (order of lines L4 and L5). If line L5 came before line L4, part 2 would include at the lookup, and for line L4 would also count the pair , which is the empty subarray . So the order of the two lines is needed for , and does no harm for .