MediumArrayHash TablePrefix Sum

1 approach, code in every language

Problem description

You are given an integer array nums and an integer k. Return the total number of contiguous subarrays whose elements add up to exactly k.

A subarray is a non-empty slice of consecutive elements. Note that the values may be negative and zero, so a longer subarray does not necessarily have a larger sum, and simply scanning for a growing window will not work.

Example 1

Input: nums = [1,1,1], k = 2

Output: 2

The subarrays [1,1] starting at index 0 and [1,1] starting at index 1 both sum to 2.

Example 2

Input: nums = [1,2,3], k = 3

Output: 2

The subarray [3] and the subarray [1,2] both sum to 3.

Constraints

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

After the pattern

Now solve one you haven't seen.

Trail Elevation Stretches is our own problem on the technique behind Subarray Sum Equals K: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free