DSA and coding Level 2 This level · 5 of 30
Medium dsa arrays

Subarray Sum Equals K

The 30 second answer

I keep a running prefix sum and a HashMap counting how many times each prefix sum has appeared, starting with zero once. At each index, the number of subarrays ending here with sum k equals how many earlier prefixes equal current sum minus k. A sliding window does not work here because values can be negative.

Could you say this in an interview?

Problem Count the contiguous subarrays whose elements add up to exactly k. Original: LeetCode 560: Subarray Sum Equals K.

Understanding the prompt "Count", not "find one". Values can be negative, which is the key detail.

Pattern recognition sum(i..j) = prefix[j] − prefix[i−1]. A target sum with negative values means prefix sum plus hash map, because the sliding-window shrink rule only works for non-negative values.

Brute force Fix each start and extend the end while keeping a running sum: O(n²).

Optimal count.put(0, 1). For each x: sum += x, ans += count.getOrDefault(sum - k, 0), then count.merge(sum, 1, Integer::sum).

Alternatives For non-negative values only, a variable sliding window works in O(1) space.

Java solution

import java.util.HashMap;

public class SubarraySumK {
    static int subarraySum(int[] nums, int k) {
        var count = new HashMap<Integer, Integer>(); // prefix sum -> occurrences
        count.put(0, 1);
        int sum = 0, ans = 0;
        for (int x : nums) {
            sum += x;
            ans += count.getOrDefault(sum - k, 0);
            count.merge(sum, 1, Integer::sum);
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(subarraySum(new int[] {1, 1, 1}, 2));      // 2
        System.out.println(subarraySum(new int[] {1, 2, 3}, 3));      // 2
        System.out.println(subarraySum(new int[] {1, -1, 0}, 0));     // 3
    }
}

Complexity O(n) expected time and O(n) space.

Edge cases

  • k = 0 with zeros and negative values: [1,-1,0] has three subarrays.
  • A subarray that starts at index 0: the initial put(0, 1) covers it.

Follow-ups

  • Return true or false only (one variant reported in a Meta onsite on LeetCode Discuss): stop at the first hit.
  • Subarray sum divisible by k: key on the remainder.
  • Longest subarray with sum k: store the first index of each prefix instead of a count.

Tests [1,1,1] with k=2 returns 2. [1,2,3] with k=3 returns 2. [1,-1,0] with k=0 returns 3.

How to say it in the interview "A sliding window fails because of negative numbers. Instead, I keep prefix sums: a subarray ending here sums to k exactly when some earlier prefix equals sum minus k. A hash map counts earlier prefixes, seeded with zero once. O(n) time and space."

Sources (3)
  1. LeetCode 560: Subarray Sum Equals Kleetcode.com
  2. Java SE 17 API: Map.mergedocs.oracle.com
  3. LeetCode Discuss: Meta E4 interview experience (candidate report, March 2025)leetcode.com
Previous
Next