Skip to main content

Subarray Sum Equals K

Medium
Data Structures and Algorithms
Editorial
Topics:
Array
Hash Table
Prefix Sum

Given an integer array nums and an integer k, consider every non-empty subarray of nums. A subarray is a contiguous sequence of one or more elements, and its sum is the total of its elements.

Return the number of distinct contiguous ranges whose elements add up to exactly k. Count each range separately, even when different ranges contain the same values.

Example 1:

Input: nums = [2,-1,2], k = 3
Output: 1
Explanation: Only the entire array has sum 3.

Example 2:

Input: nums = [4,-3,5,-2,1], k = 2
Output: 1
Explanation: The only qualifying subarray is [-3, 5], which sums to 2.

Example 3:

Input: nums = [0,0,0], k = 0
Output: 6
Explanation: Every non-empty contiguous range has sum 0, giving 3 single-element, 2 two-element, and 1 three-element subarray.

Constraints:

  • 1 <= nums.length <= 2 * 10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7
  • ``nums contains integers
  • ``k is an integer

Need help or want more practice?

Practise in an interviewGet AI Coach help