Be the first user to complete this post

  • 0
Add to List
Medium

90. Find Subarray with Sum Equal to a Target Value

Objective: Given an array (non-negative) and an integer, Find the Subarray whose sum equals 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 nested loops. Time Complexity - O(n2).

Better Approach: Time Complexity - O(n)

  • Iterate Through Array.
  • Continuously add elements starting from index 0 to the currSum.
  • While iterating through the array, check if currSum is greater than the target sum Sum.
  • Adjust Current Sum: If currSum exceeds Sum, start reducing currSum by subtracting elements from the beginning of the array using the start index.
  • While reducing currSum, check if it equals the target sum Sum. If it does, stop the iteration and return.
  • Handle End of Array: If the loop finishes without finding a subarray with a sum equal to Sum, print a message indicating that no such subarray was found.
 

Output:

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