Subarray Sum Equals K - Problem

Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

Example: In array [1,1,1] with k=2, there are 2 subarrays with sum 2: [1,1] from index 0-1 and [1,1] from index 1-2.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,1], k = 2
Output: 2
💡 Note: There are 2 subarrays with sum 2: [1,1] from index 0-1 and [1,1] from index 1-2
Example 2 — Single Element Match
$ Input: nums = [1,2,3], k = 3
Output: 2
💡 Note: Two subarrays sum to 3: [3] at index 2, and [1,2] from index 0-1
Example 3 — No Matches
$ Input: nums = [1,2,3], k = 10
Output: 0
💡 Note: No subarray sums to 10 since maximum possible sum is 1+2+3=6

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • -1000 ≤ nums[i] ≤ 1000
  • -107 ≤ k ≤ 107

Visualization

Tap to expand
Subarray Sum Equals K: Count Subarrays with Sum = 2111Target: k = 2Subarray 1: [1,1] = 2Subarray 2: [1,1] = 2Found 2 valid subarraysOutput: 2
Understanding the Visualization
1
Input
Array [1,1,1] and target sum k=2
2
Find Subarrays
Identify all contiguous subarrays that sum to k
3
Count Result
Return the total count: 2
Key Takeaway
🎯 Key Insight: Use prefix sums to transform the problem into finding pairs of sums that differ by k
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
67.3K Views
High Frequency
~18 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen