DEV Community

Debesh P.
Debesh P.

Posted on

167. Two Sum II - Input Array Is Sorted | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/solutions/7449338/most-optimal-solution-ever-beats-500-on-dqtxc


leetcode 167


Solution

class Solution {
    public int[] twoSum(int[] numbers, int target) {

        int n = numbers.length;
        int i = 0;
        int j = n - 1;

        while (i < j) {
            if (numbers[i] + numbers[j] < target) {
                i++;
            } else if (numbers[i] + numbers[j] > target) {
                j--;
            } else {
                return new int[] { i + 1, j + 1 };
            }
        }

        return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)