Explorer
Data Structures & Algorithms

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

  1. Initialize prefixMap = new Map(), currentSum = 0, and maxLen = 0.
  2. Iterate through the array with index i.
  3. Accumulate currentSum += arr[i].
  4. If currentSum === K, update maxLen = i + 1.
  5. If prefixMap.has(currentSum - K), update maxLen = Math.max(maxLen, i - prefixMap.get(currentSum - K)).
  6. Only store prefixMap.set(currentSum, i) if currentSum is not already present (we want the earliest index for maximum length).
  7. 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.

Longest Subarray with Sum K

Medium
Given an array containing both positive and negative integers and an integer K, find the length of the longest subarray having sum K.
Example Scenarios
1Example 1
Input: arr = [1, -1, 5, -2, 3], K = 3
Output: 4
Explanation:

The longest subarray is [1, -1, 5, -2].

Constraints
•Standard constraints
Editor
Loading Editor...
arr =
[1, -1, 5, -2, 3]
K =
3
Output:Click "Run" above to execute and verify your code here.
4