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
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
โ Linear Growth
Space Complexity
O(n)
Hash map can store up to n different prefix sums in worst case
โก 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code