Software Engineering Practice interview question
Given a array of N elements. Find the length of Longest Subarray whose sum is equal to given K.
This I believe is one of the most basic Problem Solving(PS) question, which I have found most people get wrong.
So I wont keep you holding for long, and here is the solution:
//Returns -1 when no sub-array has sum equal to k.
int longestSubarrayWithSumK(vector<int> inputArray, long k)
int l = 0, max_len = -1, n = inputArray.size();
for(int r = 0; r < n; r++){
long long running_sum= running_sum+ inputArray[r];
//when the running_sum overshoots the k, try to get it under K and note what the index untill where you are reducing it.
while(running_sum> k){
running_sum -= inputArray[l];
l++;
}
//Once we get the running sum equal to K, check if the current running index length of subarray is more than previously seen subarray length
if (running_sum== k){
max_len = max(max_len, r - l + 1);
}
}
return max_len;
}