Longest Subarray With Sum K

Longest Subarray With Sum K

Longest Subarray With Sum K

Problem Link:

https://www.codingninjas.com/studio/problems/longest-subarray-with-sum-k_6682399?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf&leftPanelTab=0


My Code:

  • Using Hashmap (Unordered map):

int longestSubarrayWithSumK(vector<int> a, long long k) {
    // Write your code here
    int n = a.size();
    unordered_map<long long int, int> map;

    int maxLen = 0;

    long long int sum = 0;

    for(int i=0;i<n;i++){
        sum+=a[i];
        if(sum==k){
            maxLen = max(maxLen,i+1);
        }
        else if(map.count(sum-k)>0){
            maxLen = max(maxLen, i-map[sum-k]);  
        }

        if(map.count(sum)==0){
            map[sum] = i;
        }

    }

    return maxLen;
}
  • Using Two Pointers

int longestSubarrayWithSumK(vector<int> a, long long k) {
    // Write your code here
    int n = a.size();
    int maxLen = 0;
    long long sum = a[0];

    int left = 0;
    int right = 0;

    while(right<n){
        while(left<right && sum>k){
            sum-=a[left];
            left++;
        }
        if(sum==k){
            maxLen = max(maxLen,right-left+1);
            right++;
            sum+=a[right];
        }
        else{
            right++;
            sum+=a[right];
        }

    }
    return maxLen;
}