Find the Contiguous Subarray with Sum to a Given Value in an array

Problem :

Given an array of positive integer and given value X, find Contiguous sub array whose sum is equal to X.
For example:

Solution:

Solution 1:

Check all sub arrays and if current sum is equal to X, return. This will require two loops and if currentSum is greater than X tben try another sub array.
Java code:

Time Complexity : O(N^2)

Solution 2: 

Lets say array is arr[] and given sum is X.

  • Iterate over array arr[].
  • If currentSum is less than X then add current element to currentSum.
  • If currentSum is greater than X , it means we need to remove starting elements to make currentSum less than X.
  • If CurrentSum is equal to X, we got the continuous sub array, print it.
Java Code:

Time Complexity : O(N) 

Java program to find the Contiguous Subarray with Sum to a Given Value in an array :

When you run above program , you will get below output:

Add Comment