Pages

Wednesday, March 18, 2026

167. Two Sum II - Input Array Is Sorted

1. TWO POINTER APPROACH


 class Solution {

    public int[] twoSum(int[] numbers, int target) {
        // 1. two pointer approach - initialize the var.
        int left = 0;
        int right = numbers.length-1;

        // 2. while loop until pointers meet
        while(left < right) {
            int currentSum = numbers[left]+numbers[right];

            // 3. check the sum
            if(currentSum == target) {
                return new int[] {left+1, right+1}; // why we did this, Q. asked 1-indexed array, so we add +1 in our 0-idxed array
            } if(currentSum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[] {-1, -1}; // -1 cuz exactly 1 solution
    }

   
}


2.


1. TWO POIN1. TWO POINTER APPROACHTER APPROACH

No comments:

Post a Comment

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...