Longest sub-array having sum k

Given an array arr[] of size n containing integers. The problem is to find the length of the longest sub-array having sum equal to the given value k.

Examples:

Input : arr[] = { 10, 5, 2, 7, 1, 9 }, 
            k = 15
Output : 4
The sub-array is {5, 2, 7, 1}.

Input : arr[] = {-5, 8, -14, 2, 4, 12},
            k = -5
Output : 5



Naive Approach: Consider the sum of all the sub-arrays and return the length of the longest sub-array having sum ‘k’. Time Complexity is of O(n^2).

Efficient Approach: Following are the steps:

  1. Initialize sum = 0 and maxLen = 0.
  2. Create a hash table having (sum, index) tuples.
  3. For i = 0 to n-1, perform the following steps:
    1. Accumulate arr[i] to sum.
    2. If sum == k, update maxLen = i+1.
    3. Check whether sum is present in the hash table or not. If not present, then add it to the hash table as (sum, i) pair.
    4. Check if (sum-k) is present in the hash table or not. If present, then obtain index of (sum-k) from the hash table as index. Now check if maxLen < (i-index), then update maxLen = (i-index).
  4. Return maxLen.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the length
// of longest subarray having sum k
#include <bits/stdc++.h>
using namespace std;
  
// function to find the length of longest
// subarray having sum k
int lenOfLongSubarr(int arr[], 
                    int n,
                    int k)
{
  
    // unordered_map 'um' implemented 
    // as hash table
    unordered_map<int, int> um;
    int sum = 0, maxLen = 0;
  
    // traverse the given array
    for (int i = 0; i < n; i++) {
  
        // accumulate sum
        sum += arr[i];
  
        // when subarray starts from index '0'
        if (sum == k)
            maxLen = i + 1;
  
        // make an entry for 'sum' if it is
        // not present in 'um'
        if (um.find(sum) == um.end())
            um[sum] = i;
  
        // check if 'sum-k' is present in 'um'
        // or not
        if (um.find(sum - k) != um.end()) {
  
            // update maxLength
            if (maxLen < (i - um[sum - k]))
                maxLen = i - um[sum - k];
        }
    }
  
    // required maximum length
    return maxLen;
}
  
// Driver Code
int main()
{
    int arr[] = {10, 5, 2, 7, 1, 9};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 15;
    cout << "Length = "
         << lenOfLongSubarr(arr, n, k);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the length
// of longest subarray having sum k
import java.io.*;
import java.util.*;
  
class GFG {
  
      // function to find the length of longest
      // subarray having sum k
      static int lenOfLongSubarr(int[] arr, int n, int k)
      {
             // HashMap to store (sum, index) tuples
             HashMap<Integer, Integer> map = new HashMap<>();
             int sum = 0, maxLen = 0;
  
             // traverse the given array
             for (int i = 0; i < n; i++) {
                  
                  // accumulate sum
                  sum += arr[i];
                  
                  // when subarray starts from index '0'
                  if (sum == k)
                      maxLen = i + 1;
  
                  // make an entry for 'sum' if it is
                  // not present in 'map'
                  if (!map.containsKey(sum)) {
                      map.put(sum, i);
                  }
  
                  // check if 'sum-k' is present in 'map'
                  // or not
                  if (map.containsKey(sum - k)) {
                        
                      // update maxLength
                      if (maxLen < (i - map.get(sum - k)))
                          maxLen = i - map.get(sum - k);
                  }
             }
               
             return maxLen;             
      }
  
      // Driver code
      public static void main(String args[])
      {
             int[] arr = {10, 5, 2, 7, 1, 9};
             int n = arr.length;
             int k = 15;
             System.out.println("Length = "
                                lenOfLongSubarr(arr, n, k));
      }
}
  
// This code is contibuted by rachana soma

chevron_right


C#

// C# implementation to find the length
// of longest subarray having sum k
using System;
using System.Collections.Generic;

class GFG
{

// function to find the length of longest
// subarray having sum k
static int lenOfLongSubarr(int[] arr,
int n, int k)
{
// HashMap to store (sum, index) tuples
Dictionary map = new Dictionary();
int sum = 0, maxLen = 0;

// traverse the given array
for (int i = 0; i < n; i++) { // accumulate sum sum += arr[i]; // when subarray starts from index '0' if (sum == k) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'map' if (!map.ContainsKey(sum)) { map.Add(sum, i); } // check if 'sum-k' is present in 'map' // or not if (map.ContainsKey(sum - k)) { // update maxLength if (maxLen < (i - map[sum - k])) maxLen = i - map[sum - k]; } } return maxLen; } // Driver code public static void Main() { int[] arr = {10, 5, 2, 7, 1, 9}; int n = arr.Length; int k = 15; Console.WriteLine("Length = " + lenOfLongSubarr(arr, n, k)); } } // This code is contibuted by PrinciRaj1992 [tabbyending] Output:

Length = 4

Time Complexity: O(n).
Auxiliary Space: O(n).



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.