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.
Count the contiguous slices of a list that sum to a target.
Slices are non-empty and counted by position, so the same contents at two different offsets count twice.
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.
Run your code to check it against the sample tests. Results appear here.