January 18, 2025 |45.6K Views

Subarray with Given Sum | DSA

Explore Courseexplore course icon
Description
Discussion

To find the subarray in an array that sums up to a given target, several approaches can be utilized. The naive approach involves iterating through all possible subarrays using nested loops and checking the cumulative sum for each. This approach is simple but has a time complexity of O(n^2). If the target sum is found, the starting and ending indices of the subarray are returned; otherwise, [−1] is returned.

The expected approach leverages the sliding window technique for O(n) efficiency. Starting with an empty window, elements are added to the window until the sum equals or exceeds the target. If the sum exceeds the target, elements are removed from the start of the window until it is reduced to the target. This method is efficient for positive integers and ensures minimal computation with constant space usage.

For more details, please go through - Subarray with Given Sum