I'm trying to figure out the difference in the time complexity between these two methods:
public ArrayList<Integer> populateList(int n){
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i< n; i++)
list.add(0, i);
return list;
}
public ArrayList<Integer> populateList(int n){
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i< n; i++)
list.add(i);
return list;
}
I understand that big-o is defined in terms of worst case scenario and the worst case for an addition to an arraylist involves resizing, and thus copying all the elements into a new array. I think method 2 would be O(n^2) because for each element in the array, there is a possibility that you could have to copy all the elements into a larger array.
But I am not sure about method 1 because I am not sure about the order in which things are done. It seems like the copying elements and inserting a new element could be combined such that you wouldn't have to first add the old elements to a larger list and then shift all the elements as needed when you add the new element. If that were the case, it would seem like method 1 is O(n^2) instead of O(n^3). But is that how that works?