Find Longest subarray by Sum

Find Longest subarray by Sum

·

2 min read

Problem: You have an unsorted array arr of non-negative integers and a number s. Find the longest contiguous subarray in arr that has a sum equal to s. Return two integers that represent its inclusive bounds. If there are several possible answers, return the one with the smallest left bound. If there are no answers, return [-1].

Your answer should be 1-based, meaning that the first position of the array is 1 instead of 0.

Solution: This is a two-pointer approach problem, read out the comments in the code to get a better understanding.

int[] solution(int s, int[] arr) {

    int ans[] = {-1};    
    int begin = 0;
    int end = 0;

    // to hold the current sum of the array
    int sum = 0;
    // to hold the max length of array so far
    int length = 0;

    while(end < arr.length) {
        // keep adding new elements to sum array
        sum = sum + arr[end];
        // until it becomes greater than the given sum then keep reducing from the start
        while(begin < end && sum > s) {
            sum = sum - arr[begin];
            begin++;
        }
        // if at any point we have gotten the desired sum, and the current array length is greater than the given length, 
        if (sum == s && (end - begin + 1 > length)) {
            ans = new int[]{begin + 1, end + 1};
            // update the length
            length = end -begin+1;
        }
        end++;
    }
    return ans;
}

Time complexity - O(n) - as we are only traversing the array once.