Asked at
Subarray Sum Equals K
MediumVerifiedArrayHash MapPrefix Sum~25 min
Given nums and an integer k, return the count of contiguous subarrays whose elements sum to k. Values may be negative, so a sliding window will not work.
Track prefix sums in a hash map. The input arrives as a single object { nums, k }.
Examples
in{ nums: [1, 1, 1], k: 2 }
out2
[1,1] appears at indices 0..1 and 1..2.
in{ nums: [1, 2, 3], k: 3 }
out2
[1,2] and [3] both sum to 3.
Constraints
- 1 ≤ nums.length ≤ 2 × 10⁴
- -1000 ≤ nums[i] ≤ 1000
- -10⁷ ≤ k ≤ 10⁷
- Target: O(n) time.
Get help
🔑
Sign in to solve
Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.