KatInterview

Find All Contiguous Segments with Target Total

Arrays & HashingAuto-graded · 22 test cases
HardAuto-gradedArrays & Hashingprefix-sumhash-maparray

Last updated

Tests prefix sum tracking with hash maps to efficiently count all contiguous subsequences that sum to a target value.

You are given an array of integers and a target sum. Your task is to determine how many contiguous segments of the array add up to exactly the target value.

A contiguous segment is any sequence of consecutive elements from the array. Different positions count as different segments, even if they contain the same values.

Write a function that takes the array and target sum as inputs and returns the count of valid segments.

Constraints

  • 1 <= nums.length <= 2 * 10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7

Notes

  • The array may contain negative numbers, zeros, or positive numbers
  • If no segments sum to the target, return 0
  • A single element forms a valid segment if it equals the target

Examples

Example 1

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

Output: 2

Example 2

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

Output: 2

Hints

Hint 1

Think about how to avoid checking every possible pair of start and end positions

Hint 2

Consider tracking cumulative sums as you traverse the array

Hint 3

If you know the cumulative sum up to position j and want segments ending at j that sum to k, what cumulative sum would you need at earlier positions?