For some reason, this code throws an exception "Index 20 out of bounds for length 20"
. I've tried following the code with different System.out.println to try and debug and I figured out as soon as it gets to the last cycle it goes out of bounds. I'm pretty new to java. I'm trying to understand the language and I can't get what I'm doing wrong here.
The point of this problem is to return a string using this sequence of arrays which replaces consecutive numbers with the first and the last one of a subsequence (e.g. in the example below 7,8,9,10,11 would be 7-11).
the array I've used to debug is the following:
int[] {-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}.
which should return the string= "-6,-3-1,3-5,7-11,14,15,17-20"
.
if(arr[i]+1==arr[i+1]){
while(arr[i+j]+1==arr[i+j+1]){
end=arr[i+j+1];
j++;
System.out.println("j="+j);
}
I've tried printing before this line of code and i=16
which means as soon as it finishes this iteration as j=3
i
will finally be 19 and finish the cycle. (since the 27th line "i+=j;
" should set i
to 19).
Hope I explained the problem as clearly as possible, here is the code I've written so far.
class Solution {
public static String rangeExtraction(int[] arr) {
String res="";
//int start=0;
int end=0;
int j=0;
for(int i=0;i<arr.length;i++){
System.out.println("i="+i);
if(arr[i]+1==arr[i+1]){
while(arr[i+j]+1==arr[i+j+1]){
end=arr[i+j+1];
j++;
System.out.println("j="+j);
}
if(j!=1){ res+=arr[i]+"-"+end+","; }
else{res+=arr[i]+","+end+",";}
i+=j;
j=0;
}else{
res+=arr[i]+",";
}
}
return res.substring(0,res.length()-1);
}
}