The Missing Empty Prefix

Counting contiguous subarrays whose sum equals k, using prefix sums in a hash map. It returns 3 for a = [2, 3, 1, 4, -4, 5], k = 5, but the true count is 4.

def count_subarrays(a, k):
    counts = {}
    total = 0
    result = 0
    for x in a:
        total += x
        result += counts.get(total - k, 0)
        counts[total] = counts.get(total, 0) + 1
    return result

Which subarray is missed, and what is the fix?

A

[4, -4, 5] is missed; counts must be a defaultdict(int) so absent prefixes do not read as zero

B

[2, 3] is missed; initialise counts = {0: 1} before the loop

C

[2, 3] is missed; move counts[total] = ... above the lookup so the current prefix is registered first

D

[5] is missed; the lookup should be counts.get(total + k, 0)