Predict the output
What does this print?
nums, k = [1, -1, 1], 1
prefix, seen, count = 0, {0: 1}, 0
for x in nums:
prefix += x
count += seen.get(prefix - k, 0)
seen[prefix] = seen.get(prefix, 0) + 1
print(count)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 3
Right: [1], [1] at the end, and [1, -1, 1] each sum to 1.
A window would miss the full list because shrinking on the negative value is not monotonic; prefix counts find every run.
Why not the others?
- B 2. The whole list also sums to 1.
- C 1. Two single-item runs and the full list all count.