Skip to main content
All questions
MediumArrays · Prefix Sum + Hash Map

Subarray Sum Equals K

Written by a community member · · 1 attempt · 0% pass

0

Given an integer array nums and an integer k, return the total number of non-empty contiguous subarrays whose elements sum exactly to k.

A subarray is a contiguous sequence of elements within the array. The array may contain positive, zero, and negative integers.

Constraints:

  • 1 <= len(nums) <= 2 * 10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7

Examples:

  • nums = [1, 1, 1], k = 2 returns 2 because the matching subarrays are the first two elements and the last two elements.
  • nums = [1, 2, 3], k = 3 returns 2 because the matching subarrays are [1, 2] and [3].

Aim for an O(n) time solution using O(n) additional space.