1

ques: Given an array of integers in increasing order, return an array containing positions(index+1) of two numbers that add up to a specific target number

Sol: When I write the code without using else-if for checking second condition, then I get the desired result:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left=0;
        int right=numbers.length-1;
        int arr[]=new int[2];
        while(left<right)
        {
            if(numbers[left]+numbers[right]==target)
            {
                arr[0]=left+1;
                arr[1]=right+1;
            }
             if(numbers[left]+numbers[right]<target)
            {
                left++;
            }
            else
                right--;
        }
        return arr;
        
    }
}

But when I am using else-if instead of "if" for checking the second condition, then the time limit is exceeded. Can anyone explain the reason behind this:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left=0;
        int right=numbers.length-1;
        int arr[]=new int[2];
        while(left<right)
        {
            if(numbers[left]+numbers[right]==target)
            {
                arr[0]=left+1;
                arr[1]=right+1;
            }
             else if(numbers[left]+numbers[right]<target) // using else if
            {
                left++;
            }
            else
                right--;
        }
        return arr;
        
    } }
alpha-
  • 19
  • 4
  • Hi, please write a summarized title and put the rest of the explanation in the body. Goodluck – nima Aug 25 '21 at 06:40

1 Answers1

1

The solution is incorrect. You should use break;, when you find the result in order to get out of while loop. Otherwise, you will get into infinite loop, since you will not change the left and right.

Updated solution:

class Solution {
public int[] twoSum(int[] numbers, int target) {
    int left=0;
    int right=numbers.length-1;
    int arr[]=new int[2];
    while(left<right)
    {
        if(numbers[left]+numbers[right]==target)
        {
            arr[0]=left+1;
            arr[1]=right+1;
            break;
        }
         else if(numbers[left]+numbers[right]<target) // using else if
        {
            left++;
        }
        else
            right--;
    }
    return arr;
    
} }
Burak Ozmen
  • 118
  • 6