KatInterview

Tally Contiguous Segments Matching a Goal Total

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

Last updated

Count contiguous non-empty segments of an integer array whose sum equals a goal, using running totals and a frequency map to handle negatives and zeros in linear time.

Tally Contiguous Segments Matching a Goal Total

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

A segment is a non-empty run of neighboring elements taken in their original order. Two segments are considered different if they have different start or end positions, even if they contain identical numbers. Overlapping segments are each counted separately.

Input

  • values: a list of integers.
  • goal: an integer.

Output

Return a single integer: the number of segments values[i..j] (with 0 <= i <= j < len(values)) whose sum equals goal.

Notes

  • Elements may be negative, zero, or positive, so running totals do not always grow in one direction.
  • Segments that begin at index 0 must be counted.
  • Arrays containing many zeros can produce many overlapping segments with the same sum; all of them count.

Constraints

  • 1 <= len(values) <= 10^5
  • -1000 <= values[i] <= 1000
  • -10^7 <= goal <= 10^7

Examples

Example 1

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

Output: 2

Example 2

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

Output: 3

Hints

Hint 1

Think about the running total up to each position. How can the sum of a segment be written as a difference of two running totals?

Hint 2

For each end position, you need the number of earlier running totals equal to (current total - goal). What data structure answers 'how many times have I seen this value' in O(1)?

Hint 3

Seed your frequency map with the empty running total 0, and look up the needed value before recording the current total, so that empty segments are never counted.