KatInterview

Count Contiguous Segments Summing to K

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

Last updated

Tests efficient subarray counting using prefix sum differences tracked in a hash map.

You are given an array of integers and a target value. Your task is to determine how many contiguous segments (subarrays) within the array have elements that sum exactly to the target value.

A contiguous segment is any sequence of consecutive elements from the array. For example, in [1, 2, 3], the contiguous segments are [1], [2], [3], [1, 2], [2, 3], and [1, 2, 3].

Write a function that takes an integer array and a target integer, then returns the count of all contiguous segments whose elements sum to the target.

Constraints

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

Examples

Example 1

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

Output: 2

Example 2

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

Output: 2

Hints

Hint 1

Consider computing cumulative sums as you iterate through the array. How can earlier cumulative values help count segments ending at the current position?

Hint 2

If a segment from index i+1 to j sums to target, what relationship exists between the cumulative sum at position j and the cumulative sum at position i?

Hint 3

Use a hash map to track how many times each cumulative sum has appeared. Don't forget to handle segments that start from index 0.