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 INPUT Array nums: 1 idx 0 1 idx 1 1 idx 2 Target k: 2 Subarrays with sum = 2: [1,1] idx 0-1 [1,1] idx 1-2 nums = [1, 1, 1] k = 2 ALGORITHM (Hash Map) 1 Initialize map={0:1}, sum=0, count=0 2 For each element Add to running sum 3 Check (sum - k) If in map, add to count 4 Update map Store prefix sum freq Prefix Sum Map: Key Count 0 1 1 1 2 1 3 1 FINAL RESULT Total subarrays found: 2 Execution Trace: i=0: sum=1, 1-2=-1 not in map count=0, map={0:1,1:1} i=1: sum=2, 2-2=0 in map! count=1, map={0:1,1:1,2:1} i=2: sum=3, 3-2=1 in map! count=2, map={0:1,1:1,2:1,3:1} Final count = 2 Output: 2 [OK] Key Insight: Use prefix sum with hash map: if sum[0..j] - sum[0..i-1] = k, then sum[i..j] = k. By storing prefix sum frequencies, we count how many previous positions give sum-k, achieving O(n) time complexity instead of O(n^2) brute force. TutorialsPoint - Subarray Sum Equals K | Hash Map Approach
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