DSA · Prefix sum + hashing · #29
Subarray Sum Equals K
Module 32 · difficulty 3/5·⏱ 30:00starts on first keystroke
Given an integer array `nums` and an integer `k`, return the total number of contiguous subarrays whose elements sum to exactly `k`. The array can contain negative numbers, so a sliding window does not work — you need prefix sums.
Examples
nums = [1,1,1], k = 2→2— the two [1,1] windowsnums = [1,2,3], k = 3→2— [1,2] and [3]nums = [1,-1,0], k = 0→3
Stuck? Reveal an animated walkthrough of the approach.
Constraints
- · 1 <= nums.length <= 2·10^4
- · -1000 <= nums[i] <= 1000
- · -10^7 <= k <= 10^7
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.