Asked at Tower Research Capital
Theory: Algorithms Under a Complexity BoundRead the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.
Available in Python and C++. You are solving it in Python. Switch to C++
Count the contiguous slices of a sequence of integers that sum to a target.
Slices are non-empty and counted by position, so the same contents at two different offsets count twice.
def count_subarrays(values: list[int], target: int) -> int: ...
count_subarrays([1, 1, 1], 2) # 2
count_subarrays([3, 4, 7, 2, -3, 1, 4, 2], 7) # 4
count_subarrays([0, 0, 0], 0) # 6
The zeros case is worth checking against your intuition: every pair of endpoints in a run of three zeros gives a slice summing to zero, and there are six of them.