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 Subarray found from index 2 to 4
Explanation
Two pointers track the window boundaries: as the end pointer extends the window and adds to sum, the start pointer moves forward to shrink the window whenever the sum exceeds the target, efficiently finding a subarray with the target sum.