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

how to become red on codeforces by Errichto Algorithms | explained simply in a blog

 Yes. I found an available transcript of the video and summarized it simply. The video is “How To Become Red Coder? (codeforces.com)” by Err...