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

Count Subarrays With Sum K

Written by a community member ·

0

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

A subarray consists of consecutive elements. The array may contain negative numbers, zeroes, and positive numbers.

Constraints: 0 <= len(nums) <= 100,000; -10^9 <= nums[i], k <= 10^9. Aim for O(n) time.

Example 1:
Input: nums = [1, 1, 1], k = 2
Output: 2
Explanation: The two matching subarrays are [1, 1] at the beginning and [1, 1] at the end.

Example 2:
Input: nums = [1, 2, 3], k = 3
Output: 2
Explanation: The matching subarrays are [1, 2] and [3].

Follow-ups:

  1. How would you return the longest subarray whose sum is k?
  2. How would your approach change if the array contained only non-negative numbers and you needed to count subarrays with sum at most k?
  3. What changes would be needed to process a very large stream of values without keeping the entire array in memory?