Subarray with Given Sum using Two Pointers

This program finds subarray with given sum using two pointers.

Problem Statement

Write a Java program to find subarray with sum equal to 11 using two pointers.

Source Code

1 public class SubarraySumTwoPointers {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Subarray Sum Two Pointers");
4 int[] arr = {1,2,3,7,5};
5 int target=11, start=0, sum=0;
6 for(int end=0;end<arr.length;end++){
7 sum+=arr[end];
8 while(sum>target && start<end){
9 sum-=arr[start++];
10 }
11 if(sum==target){
12 System.out.println("Subarray found from index "+start+" to "+end);
13 return;
14 }
15 }
16 System.out.println("No subarray found");
17 }
18 }

Program Output

Eduinq Subarray Sum Two Pointers
No subarray found

Explanation

Two pointers track window boundaries. - Sum adjusted by moving start pointer. - Efficiently finds subarray with target sum. - For this array no contiguous subarray adds up to 11, so the program prints No subarray found. Conclusion: Demonstrates two pointer technique for subarray sum.

Quick Links to Explore