Back to Practice
#0290

Subarray Sum Equals K

MediumDSA28 min20 XP

Problem

Given nums and k, return the number of contiguous subarrays with sum exactly k.

Why This Matters

Prefix-sum counting is the key pattern when negative numbers make sliding windows invalid.

Function Signature

def subarray_sum(nums, k):

Examples

Example 1
Inputnums = [1,1,1], k = 2
Output2

The first two and last two elements both sum to 2.

Constraints

  • Return the exact requested value.
  • Handle edge cases cleanly.
  • Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Two subarrays
Input[1,1,1], k = 2
Expected2

There are two length-2 windows.

Negative values
Input[1,-1,0], k = 0
Expected3

[1,-1], [1,-1,0], and [0] all sum to zero.

Hidden Test Categories
empty inputall zerostarget negative