Longest Subarray with Sum at most S II in O(n) Time Complexity using JavaScript


Given an array of positive integers and a number S, find the longest contiguous subarray having the sum at most S.

Return the start and end indices denoting this subarray.

Example

Input: nums = [3, 2, 5, 2, 2, 1, 1, 3, 1 , 2], S = 11
Output: [3, 8]
Explanation:the subarray nums[3...8] of sum 10

Note:

Your algorithm should run in O(n) time and use O(1) extra space.


Problem Definition

The problem requires finding the longest contiguous subarray within a given array of positive integers such that the sum of the subarray is at most a given number S. The output should be the start and end indices of this subarray.

Input

Output

Constraints

Example

Input: nums = [3, 2, 5, 2, 2, 1, 1, 3, 1, 2], S = 11
Output: [3, 8]
Explanation: The subarray nums[3...8] has a sum of 10, which is the longest subarray with sum at most 11.

Understanding the Problem

The core challenge is to find the longest subarray whose sum does not exceed a given value S. This problem is significant in various applications such as resource allocation, budgeting, and data analysis where constraints on sums are common.

Potential pitfalls include misunderstanding the requirement for the subarray to be contiguous and not considering edge cases where the entire array might be the solution.

Approach

To solve this problem, we can use the sliding window technique. This approach allows us to maintain a window of elements that we expand and contract to find the optimal subarray.

Naive Solution

A naive solution would involve checking all possible subarrays and their sums, which would result in a time complexity of O(n^2). This is not optimal for large arrays.

Optimized Solution

The sliding window technique provides an optimized solution. The idea is to use two pointers to represent the current window of elements. We expand the window by moving the end pointer and contract it by moving the start pointer to ensure the sum remains within the limit S.

Algorithm

  1. Initialize two pointers, start and end, both set to 0.
  2. Initialize variables to keep track of the current sum and the maximum length of the subarray found.
  3. Iterate through the array using the end pointer.
  4. Add the current element to the current sum.
  5. While the current sum exceeds S, increment the start pointer and subtract the element at the start pointer from the current sum.
  6. Update the maximum length and the start and end indices if the current window is longer than the previously found window.
  7. Return the start and end indices of the longest subarray.

Code Implementation

// Function to find the longest subarray with sum at most S
function longestSubarrayWithSumAtMostS(nums, S) {
    let start = 0, end = 0;
    let currentSum = 0;
    let maxLength = 0;
    let result = [-1, -1];

    // Iterate through the array
    while (end < nums.length) {
        // Add the current element to the current sum
        currentSum += nums[end];

        // While the current sum exceeds S, move the start pointer
        while (currentSum > S) {
            currentSum -= nums[start];
            start++;
        }

        // Update the maximum length and result indices if needed
        if (end - start + 1 > maxLength) {
            maxLength = end - start + 1;
            result = [start, end];
        }

        // Move the end pointer to the right
        end++;
    }

    return result;
}

// Example usage
const nums = [3, 2, 5, 2, 2, 1, 1, 3, 1, 2];
const S = 11;
console.log(longestSubarrayWithSumAtMostS(nums, S)); // Output: [3, 8]

Complexity Analysis

The time complexity of the sliding window approach is O(n) because each element is processed at most twice (once by the end pointer and once by the start pointer). The space complexity is O(1) as we are using a constant amount of extra space.

Edge Cases

Potential edge cases include:

Testing

To test the solution comprehensively, consider the following test cases:

Thinking and Problem-Solving Tips

When approaching such problems, consider the following tips:

Conclusion

In this blog post, we discussed how to find the longest subarray with sum at most S using the sliding window technique. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for developing strong problem-solving skills in programming.

Additional Resources

For further reading and practice, consider the following resources: