Two Pointer



Two Pointer Approch

// Two Sum o(n) for sorted 

public int[] getSum(int[] arr, int target){


    int left = 0;

    int right = arr.length - 1;


    while(left < right){


        int currentSum = arr[left] + arr[right];


        if(currentSum == target){

            return new int[]{left, right};

        }

        else if(currentSum > target){

            right--;

        }

        else{

            left++;

        }

    }


    return new int[]{-1, -1};

}







// for non sorted 

import java.util.HashMap;


public int[] getSum(int[] arr, int target){


    HashMap<Integer,Integer> map = new HashMap<>();


    for(int i = 0; i < arr.length; i++){


        int complement = target - arr[i];


        if(map.containsKey(complement)){

            return new int[]{map.get(complement), i};

        }


        map.put(arr[i], i);

    }


    return new int[]{-1,-1};

}


Comments