Find the length of the longest subarray with a given sum K (array can contain negative integers).
Problem Statement
Given an array containing both positive and negative integers and an integer K, find the length of the longest subarray having sum K.
Examples
Input: arr = [1, -1, 5, -2, 3], K = 3
Output: 4
Explanation: The longest subarray is [1, -1, 5, -2].
Constraints
Standard constraints
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
š” Hint 1:
Use a prefix sum hash map to store the earliest index where each prefix sum was seen.
š” Hint 2:
If currentSum === K, the subarray from index 0 to i has sum K (length = i + 1).
š” Hint 3:
If (currentSum - K) was seen at index j, the subarray from index j + 1 to i has sum K (length = i - j).
Editorial & Approach
Problem Overview & Intuition
Using the prefix sum property, if the cumulative sum up to index i is S, and the sum up to index j is S - K, then the subarray from j + 1 to i has sum K. By caching the earliest occurrence of each prefix sum in a hash map, we maximize i - j in O(N) time.
Step-by-Step Approach
- Initialize
prefixMap = new Map(),currentSum = 0, andmaxLen = 0. - Iterate through the array with index
i. - Accumulate
currentSum += arr[i]. - If
currentSum === K, updatemaxLen = i + 1. - If
prefixMap.has(currentSum - K), updatemaxLen = Math.max(maxLen, i - prefixMap.get(currentSum - K)). - Only store
prefixMap.set(currentSum, i)ifcurrentSumis not already present (we want the earliest index for maximum length). - Return
maxLen.
Optimal Implementation (JavaScript)
function longestSubarrayWithSumK(arr, K) {
const prefixMap = new Map();
let currentSum = 0;
let maxLen = 0;
for (let i = 0; i < arr.length; i++) {
currentSum += arr[i];
if (currentSum === K) {
maxLen = i + 1;
}
const needed = currentSum - K;
if (prefixMap.has(needed)) {
maxLen = Math.max(maxLen, i - prefixMap.get(needed));
}
if (!prefixMap.has(currentSum)) {
prefixMap.set(currentSum, i);
}
}
return maxLen;
}
Complexity Analysis
Time Complexity
O(N) ā single pass with O(1) hash map operations.
Space Complexity
O(N) ā hash map storing prefix sums.
Edge Cases & Corner Traps Handled
- Negative values in array: fully supported by prefix map.
- No subarray sums to K: returns 0.
- Entire array sums to K: returns arr.length.