Stretches That Hit the Goal

Medium · Prefix Sums · about 25 min

A small shop records its profit for each day in changes (a loss is negative). The owner wants to know how many stretches of consecutive days add up to exactly k.

Return the number of non-empty contiguous stretches whose total is exactly k. Two stretches are different if they start or end on a different day.

  • changes has 0 to 200,000 whole numbers and can contain zeros and negatives.
  • k can be any whole number, including 0 or negative.
  • Aim for O(n) time.

Example:

count_goal_stretches([2, -1, 1, 2, 0], 2) → 6 (the stretches are [2], [2, -1, 1], [-1, 1, 2], [2], [-1, 1, 2, 0] and [2, 0])

Hints

  • Write the sum of a stretch as the difference of two running totals.
  • At each day, you want to know how many earlier running totals equal (current total - k).
  • A map from running total to count answers that in O(1). Start it with total 0 seen once.

Learn the pattern first: the Prefix Sums lesson.

More Prefix Sums problems