KatInterview

Contiguous Subarray Sum Count

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

Last updated

Tests prefix sum technique with hash maps to count subarrays matching a target sum in linear time

You are given an array of integers nums and a target integer target. Return the total number of contiguous subarrays whose elements sum to target.

A contiguous subarray is a sequence of one or more consecutive elements from the array.

Your solution must run in O(n) time and use O(n) space.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
  • -10⁹ ≤ target ≤ 10⁹
  • The array may contain negative numbers, zeros, and positive numbers
  • Multiple subarrays may overlap

Examples

Example 1

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

Output: 2

Example 2

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

Output: 2

Example 3

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

Output: 3

Hints

Hint 1

Consider how you can use cumulative sums to transform the subarray sum problem into a simpler lookup problem

Hint 2

If the cumulative sum up to index i is S[i], what must the cumulative sum at some earlier index j be for the subarray between j and i to equal the target?

Hint 3

Use a hash map to track how many times each cumulative sum value has appeared as you iterate through the array