KatInterview

Count Contiguous Runs That Add Up to a Goal

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingprefix-sumhash-mapsubarray

Last updated

Count contiguous non-empty subarrays whose elements sum to a goal value, using running prefix sums with a frequency map to handle negatives and zeros in linear time.

You are given a list of integers values and an integer goal. Count how many contiguous, non-empty segments of values have elements that add up to exactly goal.

Segments are distinguished by their position, not by their contents. Two segments with identical contents but at different positions are counted separately. The list may contain negative numbers and zeros, and goal may be negative, zero, or positive.

Return the total number of such segments as an integer.

Constraints

  • 0 <= len(values) <= 2 * 10^4
  • -1000 <= values[i] <= 1000
  • -10^7 <= goal <= 10^7
  • An empty list contains no non-empty segments, so the answer is 0.
  • The answer can be as large as n * (n + 1) / 2.
  • Aim for O(n) expected time.

Examples

Example 1

Input: count_goal_segments([1, 1, 1], 2)

Output: 2

Example 2

Input: count_goal_segments([1, 2, 3], 3)

Output: 2

Example 3

Input: count_goal_segments([1, -1, 0], 0)

Output: 3

Hints

Hint 1

Express the sum of the segment from index i to j as the difference of two prefix sums.

Hint 2

For each position, ask how many earlier prefix sums equal (current prefix - goal). Each one corresponds to exactly one segment ending here.

Hint 3

Store how many times each prefix sum has occurred, not just whether it occurred, and start the map with prefix 0 seen once so segments beginning at index 0 are counted.