Back to DSA sheet

Subarray Sum Equals K

MediumArrays
Open on LeetCodeAmazonGoogleMetaMicrosoft

Given an integer array and a target k, count how many contiguous subarrays sum to exactly k.

Input format (stdin): the first line has n and k. The second line has n integers. Output the count.

Examples
Input: 3 2 1 1 1
Output: 2
[1,1] appears twice.
Input: 3 3 1 2 3
Output: 2
[1,2] and [3].
Constraints
  • 1 <= n <= 2*10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7
Sheets
Grind 75NeetCode 150NeetCode 250Striver A2Z
subarray-sum-equals-k.cpp3 sample tests
Loading editor
Test results

Run the sample tests to check your solution against expected output.

Custom input (stdin)
Output

Run your code to see its output.