Coding
Algorithms

Subarrays Summing to Target

Difficulty

Asked at Tower Research Capital

Theory: Algorithms Under a Complexity Bound

Read 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

Examples

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.

Constraints

  • Up to \( 2 \times 10^5 \) values, so the \( O(n^2) \) scan of every start against every end will not finish.
  • Values may be negative and may be zero, and both matter. They rule out the sliding window: extending a window no longer moves the sum in one direction, so there is no direction to shrink towards.
  • Everything is an exact integer count.
Rate this problem
Language: Pythoncount_subarrays
Sample tests

Run your code to check it against the sample tests. Results appear here.

Rate this problem