Subarray Sum Equals K - Problem
Given an array of integers nums and an integer k, find the total number of contiguous subarrays whose sum equals k. A subarray is a contiguous non-empty sequence of elements within an array. For example, in the array [1, 2, 3, 4], the subarrays are [1], [1,2], [1,2,3], [2], [2,3], [3], and so on. Your task: Count how many of these contiguous subarrays have a sum that equals the target value k.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 1, 1], k = 2
โ€บ Output: 2
๐Ÿ’ก Note: There are 2 subarrays with sum 2: [1,1] starting at index 0, and [1,1] starting at index 1
example_2.py โ€” Mixed Numbers
$ Input: nums = [1, 2, 3], k = 3
โ€บ Output: 2
๐Ÿ’ก Note: Two subarrays have sum 3: [3] at index 2, and [1,2] from indices 0-1
example_3.py โ€” Negative Numbers
$ Input: nums = [1, -1, 0], k = 0
โ€บ Output: 3
๐Ÿ’ก Note: Three subarrays sum to 0: [0], [1,-1], and [1,-1,0]

Visualization

Tap to expand
Bank Account Balance TrackerTransactions: [+3, -1, +2, -1], Target change: k = 2+3-1+2-1Running Balance (Prefix Sums):Start: $0Map: {0: 1}After +3: $3Check (3-2)=1? NoAfter -1: $2Check (2-2)=0? YES!After +2: $4Check (4-2)=2? YES!๐Ÿ’ก Key InsightIf current_balance - previous_balance = k, then the period between themhas exactly k net change. We use a hash map to quickly find previous balances!Found 2 periods: [+3,-1] and [-1,+2,-1] both sum to 2
Understanding the Visualization
1
Track Running Balance
Keep a running total (prefix sum) as we process each transaction
2
Use History
For each current balance, check if we've seen (current_balance - k) before
3
Count Periods
If we found (current - k) previously, it means there's a period with exactly k change
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking all subarrays (O(nยฒ)), we use prefix sums and hash map to find the answer in O(n) time by leveraging the mathematical relationship: prefix[j] - prefix[i] = k

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array, hash map operations are O(1) average case

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map can store up to n different prefix sums in worst case

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 2 ร— 104
  • -1000 โ‰ค nums[i] โ‰ค 1000
  • -107 โ‰ค k โ‰ค 107
  • Note: The array can contain negative numbers, zero, and positive numbers
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28 Apple 22
42.3K Views
Very High Frequency
~22 min Avg. Time
1.8K 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