Skip to content
RED SAGSkills
medium30 ptsarrayshash-map

Count Subarrays With a Given Sum

Given an integer array nums (values may be negative) and an integer k, return how many contiguous, non-empty subarrays sum to exactly k.

Example 1

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

Example 2

Input: nums = [1, 2, 3], k = 3
Output: 2
Explanation: [1, 2] and [3].

Constraints

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

A subarray (i, j] sums to k when prefix[j] - prefix[i] = k.

Hint 2

Count how many times each prefix sum has occurred so far.

Good practice for: Data Scientist, Data Engineer, Machine Learning Engineer, AI Engineer (LLM & Generative AI), Backend Developer, Full Stack Developer, Site Reliability Engineer

Run checks your code on 2 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.