DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Pattern: Two Pointer

Problems where we can use two pointers i,j to get to a solution in the given Array or String
Example : Two Sum II Input Arrays is Sorted
Here we have find two indices from the given array such that sum of those indices value is target (condition index1< index2)

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int l=  0;
        int r = numbers.length-1;
        while(l<r){
            int sum = numbers[l] + numbers[r];
            if(sum == target) return new int[]{l+1,r+1};
            else if(sum < target) l++;
            else r--;
        }
        return new int[-1];
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)