Longest Sub-Array with Sum K | Practice | GeeksforGeeks

Given an array containing N integers and an integer K., Your task is to find the length of the longest Sub-Array with the sum of the elements equal to the given value K. 
 
Example 1:
 
Input :
A[] = {10, 5, 2, 7, 1, 9}
K = 15
Output : 4
Explanation:
The sub-array is {5, 2, 7, 1}.

Example 2:
Input : 
A[] = {-1, 2, 3}
K = 6
Output : 0


Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function smallestSubsegment() that takes an array (A), sizeOfArray (n),  sum (K)and returns the required length of the longest Sub-Array. The driver code takes care of the printing.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
 
Constraints:
1<=N<=105
-105<=A[i], K<=105
 
0
harshpandeyalfa23 weeks ago
C++
(0.36 sec)
int lenOfLongSubarr(int A[],  int N, int k)    {      int ps=0;     int res=0;     unordered_map<int,int> um;     for(int i=0 ; i<N;i++)     {         ps+=A[i];         if(ps==k)          res=i+1;         if(um.find(ps) == um.end())          um.insert({ps,i});         if(um.find(ps-k) != um.end())          res=max(res, i- um[ps-k]);     }     return res;   }
 
0
hydracody453 weeks ago
I thought there are three solution
-brute force 0(n3)-cummlative sum 0(n2)-prefix sum 0(nlog(n))
-brute force 0(n3)
-cummlative sum 0(n2)
-prefix sum 0(nlog(n))
There is one more solution in0(n) with two pointers but it does not work with negative numbers.
-2
emmanueluluabuike1 month ago
Can someone explain what is wrong with my logic?
public static int lenOfLongSubarr (int arr[], int sizeOfArray, int K) {
        //Complete the function
        int left = 0, right = 0, currentRunningSum = 0, max = 0;

        while(right < sizeOfArray){
            currentRunningSum += arr[right];
            
            if(currentRunningSum == K)
                max = Math.max(max, (right + 1) - left);

            if(currentRunningSum >= K){
                currentRunningSum -= arr[left];
                left++;
            }
            
            right++;
        }
        
        return max;
    }
+1
ravi1010prakash2 months ago
class Solution{   public:   int lenOfLongSubarr(int A[],  int N, int K)    {        // Complete the function       unordered_map<int,int>mp;       int presum=0;       int res=0;       for(int i=0;i<N;i++)       {           presum+=A[i];           if(presum==K)           res=i+1;           if(mp.find(presum)==mp.end())           mp.insert({presum,i});           if(mp.find(presum-K)!=mp.end())           res=max(res,i-mp[presum-K]);       }       return res;   }
};
0
nirbhayg3422 months ago
Most Efficient solution (0.2/1.7)
 
class Solution{   public:   int lenOfLongSubarr(int A[],  int N, int K)    {        // Complete the function       int res=0;       unordered_map<int,int>m;       int pre_sum=0;       for(int i=0;i<N;i++){           pre_sum+=A[i];           if(pre_sum==K){res=i+1;}           if(m.find(pre_sum)==m.end()){               m.insert({pre_sum,i});           }           if(m.find(pre_sum-K)!=m.end()){               res=max(res,i-m[pre_sum-K]);           }       }       return res;   } 
0
gagandeepsingh2972 months ago
Test Cases Passed:
193 / 193
Total Points Scored:
4/4
Total Time Taken:
0.2/1.7
Your Accuracy:
100%
 
 
 unordered_map<int, int> m;       int p = 0;       m.insert({0, -1});       int len = 0;       for(int i=0; i<n; i++){           p += A[i];           if(m.find(p-K) != m.end()){               len = max(len, i-m[p-K]);           }           if(m.find(p) == m.end()){               m[p] = i;           }       }       return len;
 
+1
sg6214282 months ago
class Solution{
    // Function for finding maximum and value pair
    public static int lenOfLongSubarr (int A[], int N, int K) {
        int cursum=0;
        int start=0;
        int end=-1;
        int max=0;
        Map<Integer,Integer>map=new HashMap<>();
        for(int i=0;i<A.length;i++)
        {
            cursum+=A[i];
            if(cursum-K==0)
            {
                start=0;
                end=i;
                if((end-start+1)>max)//comparing subarray size 
                max=end-start+1;
            }
            if(map.containsKey(cursum-K))
            {
                start=map.get(cursum-K)+1;
                end=i;
                if((end-start+1)>max)
                max=end-start+1;
            }
            if(map.containsKey(cursum))//if we get two same keys with different values
            map.getOrDefault(cursum,0);
            else
            map.put(cursum,i);
        }
        return max;
    }
}

0
shreyansh00022 months ago
int lenOfLongSubarr(int A[],  int N, int K)    {        unordered_map<int,int>m;       int pre_sum = 0, res = 0;       for(int i = 0; i<N; i++){           pre_sum += A[i];           if(pre_sum == K)                res = i+1;           if(m.find(pre_sum) == m.end())               m.insert({pre_sum, i});           if(m.find(pre_sum - K) != m.end())               res = max(res, i-m[pre_sum-K]);       }       return res;   }  
0
choudharysdimple123453 months ago
class Solution{   public:   int lenOfLongSubarr(int A[],  int N, int K)    {    int sum=0;   unordered_map<int,int> vec;      int i=0,j=0,mx=0;      for(int i=0;i<N;i++){       sum += A[i];       if(sum == K) mx = max(mx,i+1);       if(vec.find(sum) == vec.end()) vec[sum] = i;       if(vec.find(sum - K) != vec.end()) mx = max(mx,i-vec[sum - K]);   }      return mx;   }
};
0
aloksinghbais023 months ago
C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :-
Note :- Similar question in which we find total number of subarrays with given sum.
 
Execution Time :- 0.4 /1.7 sec
 
int lenOfLongSubarr(int A[],  int N, int K){        unordered_map<int,int> firstLastInd;       unordered_map<int,bool> mp;       int len = 0;       int sum = 0; mp[0] = true, firstLastInd[0] = 0;       for(int i=0; i<N; i++){           sum += A[i];           if(mp[sum-K]){               len = max(len,i - firstLastInd[sum-K] + 1);           }                      mp[sum] = true;           if(firstLastInd[sum] == 0 && sum)                                       firstLastInd[sum] = i+1;       }              return (len);   } 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.