Skip to content

Interview Solver

FeaturesPricingHelp
Sign In
FeaturesPricingHelpSign In
  1. Interview Questions
  2. /
  3. Problems
  4. /
  5. Subarray Sum Equals K

Subarray Sum Equals K

Count the contiguous subarrays that add up to k, with negatives allowed. The standard prefix-sum plus hash map counting trick. Solve it below in Python or JavaScript, then read the walkthrough.

MediumArrayHash TablePrefix SumAsked at 123 companies incl. Google, Amazon, Meta

Problem

Given an integer array nums and an integer k, return how many contiguous, non-empty subarrays of nums have a sum equal to k.

Subarrays at different positions count separately, even if they contain the same values. The array can contain negative numbers and zeros.

Example 1

Input
nums = [3, 1, 2, 4], k = 3
Output
2

The subarrays [3] and [1, 2] each sum to 3.

Example 2

Input
nums = [1, -1, 1, -1], k = 0
Output
4

[1, -1] appears at positions 0–1 and 2–3, [-1, 1] at 1–2, and the whole array also sums to 0.

Example 3

Input
nums = [5, 5, 5], k = 10
Output
2

Constraints

  • 1 ≤ nums.length ≤ 2 × 10⁴
  • -1000 ≤ nums[i] ≤ 1000
  • -10⁷ ≤ k ≤ 10⁷

Practice

1
2
3
4

Runs 12 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.

Get asked Subarray Sum Equals K in a real interview?

Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.

Start Free Trial

How to solve Subarray Sum Equals K

Pattern: Prefix sums + hash map of counts

Write prefix[j] for the sum of the first j elements. The sum of the subarray from i to j - 1 is prefix[j] - prefix[i]. So "this subarray sums to k" is the same as "some earlier prefix equals prefix[j] - k".

That turns the problem into Two Sum over prefix sums. Walk the array keeping a running total, and keep a map from each prefix value to how many times you've seen it. At each step, add count[total - k] to the answer, then record the current total. Seed the map with {0: 1} for the empty prefix, so subarrays that start at index 0 are counted.

Why not a sliding window? Windows rely on the sum growing when you extend and shrinking when you shrink. With negative numbers that's false, so a window can't know which way to move. Prefix sums don't care about signs.

Approach 1: Brute force over every subarray

For each start i, extend the end j one step at a time while keeping a running sum, and count every time it equals k. No extra memory, but it visits all n(n + 1)/2 subarrays.

Time O(n²) · Space O(1)

Approach 2: Prefix sums with a counting map

  1. Set count = {0: 1}, total = 0, answer = 0.
  2. For each x in nums: total += x, then answer += count.get(total - k, 0), then count[total] += 1.
  3. Return answer.

Looking up before inserting means the current prefix never pairs with itself, so every match is a non-empty subarray.

Time O(n) · Space O(n)

ApproachTimeSpace
Brute force over every subarrayO(n²)O(1)
Prefix sums with a counting mapO(n)O(n)

Solution code

Try the practice editor first. Both solutions pass every test above.

▸Subarray Sum Equals K solution in Python
def subarray_sum(nums: list[int], k: int) -> int:
    count = {0: 1}  # prefix sum -> times seen
    total = 0
    answer = 0
    for x in nums:
        total += x
        answer += count.get(total - k, 0)
        count[total] = count.get(total, 0) + 1
    return answer
▸Subarray Sum Equals K solution in JavaScript
function subarraySum(nums, k) {
  const count = new Map([[0, 1]]); // prefix sum -> times seen
  let total = 0;
  let answer = 0;
  for (const x of nums) {
    total += x;
    answer += count.get(total - k) ?? 0;
    count.set(total, (count.get(total) ?? 0) + 1);
  }
  return answer;
}

Common mistakes

  • Forgetting to seed the map with `{0: 1}`, which misses every subarray that starts at index 0.
  • Storing whether a prefix was seen instead of how many times, which undercounts when prefixes repeat (zeros, or values that cancel out).
  • Inserting the current prefix before the lookup, which counts the empty subarray when k = 0.
  • Reaching for a sliding window, which only works when every number is positive.

What interviewers look for

Start with the O(n²) running-sum loop, then point at its inner loop: "for each end, I'm searching for starts whose prefix equals total - k." Once you say that sentence, the hash map is the obvious fix, and the interviewer hears that you got there by reasoning rather than recall.

Explain why a sliding window fails before anyone asks, using a quick example with a negative number. Then trace the map on [1, -1, 1, -1], k = 0, to show the counts (not booleans) matter.

Follow-up questions

What if all numbers are positive?

Then a sliding window works in O(1) extra space: grow the right end, and while the sum exceeds k, shrink from the left. Count each time the sum equals k exactly.

How would you return the length of the longest subarray with sum k?

Store the first index where each prefix value appears instead of a count. At index j, if total - k was seen at index i, the candidate length is j - i. Keeping only the first occurrence maximizes the length.

How would you count subarrays whose sum is divisible by k?

Use the same idea with prefix sums modulo k: two prefixes with the same remainder bound a subarray divisible by k. Count remainders, normalizing negatives to the range 0..k - 1.

Companies that ask Subarray Sum Equals K

Subarray Sum Equals K is tagged by 123 companies in our interview dataset. The score shows how often it comes up at each company.

  • PointClickCare100%
  • Samcart100%
  • Crunchbase100%
  • Wolters Kluwer100%
  • Paylocity100%
  • Ricoh Usa96%
  • Credit Karma95%
  • And Digital94%
  • 23andme94%
  • Viasat92%
  • Kraken Technologies92%
  • Harman International88%
  • Meta87.2%
  • AMD85.9%
  • Coforge85%
  • Abbvie85%
  • Bandwidth83%
  • Revature82%
  • Ancestry82%
  • 1password81%
  • Buffer79%
  • Yandex78.5%
  • Thg78%
  • Accenture77%

and 99 more.

Practice next

  • Two SumEasyHash map of complements
  • Group AnagramsMediumHash map keyed by a canonical form
  • Top K Frequent ElementsMediumCount, then bucket by frequency
  • Product of Array Except SelfMediumPrefix and suffix products

Get live help in the real interview

Working solutions in real time during your actual interview. Invisible to screensharing.

Start Free Trial

No credit card required

Interview Solver
  • Home
  • About
  • Pricing
  • Sign in
  • Contact
  • Blog
  • Companion
  • Mobile
  • Help Center
  • Developers
  • Use Cases
  • Software Engineer
  • Product Manager
  • Misc
  • Privacy Policy
  • Terms and Conditions
  • Refund & Cancellation
  • Discord Community
  • Affiliate Program
  • Compare
  • All Comparisons
  • vs Final Round AI
  • vs UltraCode
  • vs Interview Coder
  • vs LockedIn AI
  • vs AI Apply
  • Free Tools
  • ATS Resume Checker
  • STAR Method Builder
  • Salary Lookup
  • Big O Cheat Sheet
  • Total Comp Calculator
  • View All →
  • Interview Questions
  • Google Questions
  • Amazon Questions
  • Microsoft Questions
  • Meta Questions
  • Apple Questions
  • TikTok Questions
  • View All →
© 2026 Interview Solver, Inc. All rights reserved.