Editorial for Subarray Sums


Approach

Let pip_i be the prefix sum of the first ii elements, with p0=0p_0 = 0. The sum of the subarray from ll to rr is pr−pl−1p_r - p_{l-1}.

So when we are at a prefix sum prp_r, we need to know how many earlier prefix sums equal pr−xp_r - x. Every such earlier prefix sum gives one subarray ending at rr whose sum is xx.

We scan the array from left to right, maintain the current prefix sum, and store how many times each prefix sum has appeared in a dictionary.

This is O(n)O(n) time.

Solution (Python)

Code 1
n, x = map(int, input().split())
values = list(map(int, input().split()))

seen = {0: 1}
prefix = 0
answer = 0

for value in values:
    prefix += value
    answer += seen.get(prefix - x, 0)
    seen[prefix] = seen.get(prefix, 0) + 1

print(answer)

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.