19. Subarray with given sum
The problem can be found at the following link: Question Link
My Approach
To solve this I am using a two-pointer approach to find the subarray with the given sum.
Initialize two pointers,
i
andj
, for starting and ending pointers respectively. Initially, both point to the beginning of the array.Initialize a variable
sum
to keep track of the current sum of elements betweeni
andj
.Iterate through the array with ending pointer
j
, adding each element tosum
.If
sum
becomes greater than the target sums
, incrementi
and subtractarr[i]
fromsum
untilsum
is less than or equal tos
.If
sum
becomes equal tos
, we have found a subarray with the given sum. Record the indicesi+1
andj+1
(1-based indices) and return them.
If the loop completes without finding a subarray, return
[-1]
to indicate no such subarray exists.
Explanation with Example
Suppose we have an array arr = [1, 2, 3, 7, 5]
and the target sum s = 12
.
so the answer for the above example is 2, 4
.
Time and Auxiliary Space Complexity
Time Complexity: The algorithm uses a single pass through the array, so the time complexity is
O(n)
, wheren
is the size of the input array.Auxiliary Space Complexity: The algorithm uses a constant amount of extra space for variables, so the auxiliary space complexity is
O(1)
.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated