Subarray Sum Equals K

MediumArrays & Hashingprefix sum + hashmap

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums and an integer k, return the total number of **contiguous subarrays** whose elements sum to exactly k. A subarray is a non-empty slice of consecutive elements from the array. Two subarrays are considered different if they start or end at different indices, even when they contain the same values. Note that nums may contain negative numbers and zeros, so a simple sliding window will not work — the running sum is not guaranteed to increase as the window grows. A naive approach checks every (start, end) pair in O(n^2) time. Aim for an O(n) solution that scans the array once while tracking how often each running prefix sum has been seen.

Examples

Input: nums = [1,1,1], k = 2
Output: 2
The subarrays nums[0..1] and nums[1..2] each sum to 2.
Input: nums = [1,2,3], k = 3
Output: 2
The subarray [3] (index 2) and the subarray [1,2] (indices 0..1) both sum to 3.
Input: nums = [3,4,7,2,-3,1,4,2], k = 7
Output: 4
Four subarrays sum to 7: [3,4], [7], [7,2,-3,1], and [1,4,2].

Constraints

  • 1 <= nums.length <= 2 * 10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7
  • Subarrays must be contiguous and non-empty.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.