VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-subarray-with-given-sum/

⇱ Subarray with Given Sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Subarray with Given Sum

Last Updated : 6 Apr, 2026

Given a 1-based indexing array arr[] of non-negative integers and an integer sum. Find the left and right indexes(1-based indexing) of that subarray that is equal to the given sum. In case of multiple subarrays, find the subarray indexes which come first on moving from left to right. If no such subarray exists return an array consisting of element -1.

Examples:

Input: arr[] = [15, 2, 4, 8, 9, 5, 10, 23], target = 23
Output: [2, 5]
Explanation: Sum of subarray arr[2...5] is 2 + 4 + 8 + 9 = 23.

Input: arr[] = [1, 10, 4, 0, 3, 5], target = 7
Output: [3, 5]
Explanation: Sum of subarray arr[3...5] is 4 + 0 + 3 = 7.

Input: arr[] = [1, 4], target = 0
Output: [-1]
Explanation: There is no subarray with 0 sum.

[Naive Approach] Using Nested loop - O(n^2) Time and O(1) Space

  • Use a nested loop where the outer loop selects the starting index of the subarray.
  • The inner loop keeps adding elements to a running sum starting from that index.
  • If the sum equals the target, return the 1-based start and end indices; otherwise, return -1 if no subarray is found.

Output
2 5 

[Expected Approach] Sliding Window - O(n) Time and O(1) Space

  • Since all elements are positive, subarray (or window) sum increases subarray is expanded.
  • Expand the window while the sum is less than the target. If the sum exceeds the target, shrink from the left; if equal, return the subarray.

Output
2 5 

[Alternate Approach] Hashing + Prefix Sum - O(n) Time and O(n) Space

  • The above sliding window solution fails when negative numbers are present, so we use prefix sum with hashing.
  • Store the prefix sum at each index in a hashmap while traversing the array.
  • If at any index currSum - target exists in the hashmap, then a subarray with the required sum exists.

To know more about the implementation, please refer Subarray with Given Sum – Handles Negative Numbers.

Comment