Why am i getting runtime error for java soln


#1

can anybody help me why am i getting this error and how to correct this:
Exception in thread “main” java.lang.IndexOutOfBoundsException: Index: 79, Size: 0
at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:665)
at java.util.ArrayList.add(ArrayList.java:477)
at Solution.generateMatrix(Solution.java:20)
at Main.main(Main.java:329)

this error comes for testing input 80 when i did custom input for A=5 then same error came for index:4.

here is my code:
public class Solution {
public ArrayList<ArrayList> generateMatrix(int A) {
ArrayList<ArrayList> formspiralmatrix=new ArrayList<ArrayList>();
int left=0,right=A-1,top=0,bottom=A-1;
for(int i=0;i<A;i++)
{
formspiralmatrix.add(new ArrayList());
}
int n=1;
while(top<=bottom && left<=right)
{
for(int i=left;i<=right;i++)
{
formspiralmatrix.get(top).add(i,n);
n++;
}
top++;
for(int i=top;i<=bottom;i++)
{
formspiralmatrix.get(i).add(right,n);
n++;
}
right–;
if(top<bottom){
for(int i=right;i>=left;i–)
{
formspiralmatrix.get(bottom).add(i,n);
n++;
}
bottom–;}
if(left<right)
{for(int i=bottom;i>=top;i–)
{
formspiralmatrix.get(i).add(left,n);
n++;
}
left++;}
}
return formspiralmatrix;
}
}


#2

Got this error corrected by initializing all columns with 0. but now getting wrong answer for big inputs like 80


#3

add(index, value) method of a ArrayList shifts all the elements to the right. hence it’s an O(n) operation.
This makes your overall time complexity O(n^3), which is probably why it’s failing for larger inputs.

Can you try initialising all the elements to 0 and then using ArrayList’s set(index, value) method?