Question presented to candidate: "Given a list of integers that may include negatives, and a target k, count how many contiguous subarrays sum to exactly k. Brute force is O(n squared) โ can you do it in linear time in Python?"
What a strong answer should cover:
- A subarray sum is
P[j] - P[i], so count earlier prefixes equal toprefix - k. - A count map seeded with
{0: 1}; count before recording; counts, not a set. - O(n) average time, O(n) space; brute force O(nยฒ); why a sliding window fails with negatives.
- Python specifics:
collections.Counterreturns 0 for a missing key without inserting it, unlikedefaultdict;dict.get(key, 0)also works. - Edge cases: zeros,
k = 0, subarrays starting at index 0.
Clarifying questions expected:
- "Can the array contain negatives or zeros?" โ decides between a sliding window and prefix sums.
- "Do you want the count or the subarrays themselves, and how large can the sums get?"
Code / implementation expected: Yes โ a one-pass Python function with a Counter or dict.