VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-sub-array-sum-k/

⇱ Longest Subarray With Sum K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Subarray With Sum K

Last Updated : 11 Jan, 2025

Given an array arr[] of size n containing integers, the task is to find the length of the longest subarray having sum equal to the given value k.

Note: If there is no subarray with sum equal to k, return 0.

Examples:

Input: arr[] = [10, 5, 2, 7, 1, -10], k = 15
Output: 6
Explanation: Subarrays with sum = 15 are [5, 2, 7, 1], [10, 5] and [10, 5, 2, 7, 1, -10]. The length of the longest subarray with a sum of 15 is 6.

Input: arr[] = [-5, 8, -14, 2, 4, 12], k = -5
Output: 5
Explanation: Only subarray with sum = 15 is [-5, 8, -14, 2, 4] of length 5.

Input: arr[] = [10, -10, 20, 30], k = 5
Output: 0
Explanation: No subarray with sum = 5 is present in arr[].

[Naive Approach] Using Nested Loop - O(n^2) Time and O(1) Space

The idea is to check the sum of all the subarrays and return the length of the longest subarray having the sumk.


Output
6

[Expected Approach] Using Hash Map and Prefix Sum - O(n) Time and O(n) Space

If you take a closer look at this problem, this is mainly an extension of Longest Subarray with 0 sum.

The idea is based on the fact that if Sj - Si = k (where Si and Sj are prefix sums till index i and j respectively, and i < j), then the subarray between i+1 to j has sum equal to k.
For example, arr[] = [5, 2, -3, 4, 7] and k = 3. The value of S3 - S0= 3, it means the subarray from index 1 to 3 has sum equals to 3.

So we mainly compute prefix sums in the array and store these prefix sums in a hash table. And check if currentprefix sum - k is already present. If currentprefix sum - k is present in the hash table and is mapped to index j, then subarray from j to current index has sum equal to k.

Below are the main points to consider in your implementation.

  1. If we have the whole prefix having sum equal to k, we should prefer it as it would be the longest possible till that point.
  2. If there are multiple occurrences of a prefixSum, we must store index of the earliest occurrence of prefixSum because we need to find the longest subarray.



Output
6

Related Problem

Largest subarray with equal number of 0s and 1s

Comment
Article Tags: