Magicsheet logo

Maximum Size Subarray Sum Equals k

Medium
78.7%
Updated 6/1/2025

Maximum Size Subarray Sum Equals k

1. What is this problem about?

The Maximum Size Subarray Sum Equals k coding problem asks you to find the length of the longest contiguous subarray that sums up to a specific value k. If no such subarray exists, you return 0.

2. Why is this asked in interviews?

This is a classic question from Goldman Sachs, Microsoft, and Meta. it tests the ability to optimize a brute-force O(N²) subarray search into a linear O(N) solution. It evaluates your understanding of the relationship between prefix sums and subarray sums, and your ability to use a Hash Table to look back at previously seen sums.

3. Algorithmic pattern used

This utilizes the Hash Table and Prefix Sum interview pattern. As you iterate through the array, maintain a running_sum. A subarray ending at index i sums to k if there exists a previous index j such that running_sum[i] - running_sum[j] = k. This is equivalent to running_sum[j] = running_sum[i] - k. We use a Hash Table to store the first index where each running_sum occurred.

4. Example explanation

Array: [1, -1, 5, -2, 3], k = 3.

  • Sum 0: index -1. Map: {0: -1}
  • Sum 1: index 0. Map: {0: -1, 1: 0}
  • Sum 0 (1-1): index 1. Already in map.
  • Sum 5: index 2. Map: {0: -1, 1: 0, 5: 2}
  • Sum 3: index 3. Target = 3 - 3 = 0. 0 is at -1. Length = 3 - (-1) = 4. (Subarray: [1, -1, 5, -2])
  • Sum 6: index 4. Target = 6 - 3 = 3. 3 is at ... not in map. Max length: 4.

5. Common mistakes candidates make

A common error is storing the latest index of a sum in the Hash Table instead of the earliest. To maximize the subarray length i - j, we want j to be as small as possible. Another mistake is forgetting to initialize the Hash Table with {0: -1} to handle subarrays that start from the very beginning of the array.

6. Interview preparation tip

Mastering the "Hash Table, Prefix Sum interview pattern" is vital. This technique is used in dozens of subarray problems (e.g., "Subarray Sum Equals K," "Longest Subarray with Sum Divisible by K"). Always remember: SubarraySum(i, j) = PrefixSum(j) - PrefixSum(i-1).

Similar Questions