Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Subarray Sum Equals K
Problem
Given an integer array nums and an integer k, count how many contiguous, non-empty subarrays have elements that sum to exactly k. Elements may be negative, zero, or positive.
- The array is non-empty and has at most 50,000 elements.
- Each element has magnitude at most 5,000, so every prefix sum fits in a 64-bit integer.
kcan be any value a prefix sum could take, including 0 and negatives.
Examples
nums = [2, 4, 2, 2, 4], k = 6→3.[2,4]at positions 0-1,[4,2]at 1-2, and[2,4]at 3-4.nums = [5, -3, 3, 1], k = 5→2.[5]and[5,-3,3].nums = [4, -4, 0, 4], k = 0→4.[4,-4],[4,-4,0],[0], and[-4,0,4].
Hints
- The sum of
nums[i..j]is the difference of two prefix sums. Which two? - For a fixed right end j, you want to know how many earlier prefix sums equal
P[j] - k. - Walk left to right maintaining a hash map from prefix-sum value to how many times it has occurred; seed it with
{0: 1}.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.