Skip to the solution
MediumDSA11 min read

How do you count subarrays that sum to k?

342 views

The problem

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 to prefix - 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.Counter returns 0 for a missing key without inserting it, unlike defaultdict; 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.

  • arrays
  • prefix-sum

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonPrefix sum + hash map on seven inputs
PythonBrute force vs hash map vs sliding window

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 100 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you solve the 3Sum problem?

Continue