-1

it showing me runtime error java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at line 5, Solution.twoSum

    class Solution {
    public int[] twoSum(int[] nums, int target) {
         
        for(int i=0;i<nums.length;i++){
            int result=nums[i]+nums[i+1];
            if(result==target){  
                return new int[]{i,i+1};
            }
            
           
    } 
        throw new IllegalArgumentException("No two sum solution");

    }
}
shilpi
  • 27
  • 5
  • 1
    The error tells you exactly what is wrong. Your array has size 3, which means the valid indices are 0 1 and 2, you are trying to get the 4th element of a 3-sized array – Stultuske Dec 26 '20 at 16:07
  • 1
    Fix: `for(int i = 0; i < nums.length - 1; i++) {` – 001 Dec 26 '20 at 16:09
  • 1
    Also, throwing and exception when the sum is not found might not be the best design choice. Instead, consider returning `null`. – 001 Dec 26 '20 at 16:10
  • Johnny Mopp, it not passing test case; when I am using null instead of exception – shilpi Dec 26 '20 at 16:25

1 Answers1

2

Root Cause

int result=nums[i]+nums[i+1]; 

The nums[i+1] here will always throw the java.lang.ArrayIndexOutOfBoundsException because the last index plus 1 will result in the outside permissible range index.

Solution

Modify your for loop as below:

        for(int i=1;i<nums.length;i++){
            int result=nums[i-1]+nums[i]; // you will not miss evaluating any index as per your algorithm
            if(result==target){  
                return new int[]{i-1,i}; // your required indexes will change accordingly
            }
        }
Sharad Nanda
  • 406
  • 1
  • 15
  • 27
  • thanks Sharad ... but what should I do with the return statement If use null then it doesn't pass test cases.? – shilpi Dec 26 '20 at 16:23
  • for(int i=0;i – Duane Dec 26 '20 at 16:29
  • @shilpi I understand that is one of the boundary condition where you don't find any suitable pair. It depends on your downstream function call stack what you are expecting. It could be either a dummy/placeholder object to identify this scenario of unsuccessful search or it could be surrounded by your try catch block. Maybe if you can update the question with the problem statement then I can go ahead & figure out the modification to your algorithm. – Sharad Nanda Dec 26 '20 at 17:05