In an Array, find the Contiguous Subarray with Sum to a Given Value.

Objective: Given an array and an integer, find the Subarray whose sum is equal to the given integer.

Examples:

int[] arrA = { 25, 12, 14, 22, 19, 15, 10, 23 };
Integer = 55
Output : 55 is found between indexes 2 and 4
And Elements are : 14 22 19

Approach :

Naive Approach: Use 2 loops . Time Complexity – O(n2).

Better Approach: Time Complexity – O(n)

• Idea is to keep adding all the elements to the currSum
• Keep checking if the currSum<Sum
• If currSum gets greater than the Sum then start reducing the currSum from the beginning of the array using “start”if any time currSum=Sum, Stop and return

NOTE: Technique used in this problem can be used to solve the problem “Find a subarray such that the sum of elements in it is equal to zero“. In that the array will aldo have to contain the negative elements and our given sum is zero.

Complete Code:

Output:

55 is found between indexes 2 and 4
And Elements are :  14 22 19

__________________________________________________
Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________