← Questions
Count subarrays that sum to K
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's technical phone screen, last asked Feb 2026. It tests prefix sums, hash map and arrays.
Given an integer array nums (values may be negative or zero) and an integer k, return how many contiguous, non-empty subarrays sum to exactly k.
Interface
Unless you agree on a different interface with the interviewer, assume:
count_subarrays(nums: list[int], k: int) -> int
Example
nums = [1, 2, 3], k = 3 -> 2 # [1, 2] and [3]
nums = [3, -1, 1, 0, 2], k = 3 -> 4 # [3], [3, -1, 1], [3, -1, 1, 0], [1, 0, 2]
nums = [0, 0, 0], k = 0 -> 6 # every subarray
Constraints
1 <= len(nums) <= 2 * 10^4-
-1000 <= nums[i] <= 1000,-10^7 <= k <= 10^7
Clarifying questions
- Can values be negative? (They can, so a sliding window doesn't work.)
- Do overlapping subarrays count separately?
- Do you want the count, or the subarrays themselves?
What a strong answer covers
- The O(n^2) brute force first, then running prefix sums with a hash map from each prefix sum to how many times it has appeared, O(n) time and space.
- Seeding the map with
{0: 1}so subarrays starting at index 0 count. - Updating the map after counting, not before, so the empty subarray isn't counted when
k = 0. - Why the sliding window fails with negatives.
Follow-ups
- Return the length of the longest subarray summing to
k. - Count subarrays whose sum is divisible by
k. - All values are non-negative: solve it with O(1) extra space.
Where it's asked
- Apple · Technical phone screen · Last asked Feb 2026
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
