for (int i =0; i < n; i++){
lst.add(lst.size()/2,3*i);
}
I was thinking that the for loop will take o(n) but I was not clear what what the difference between add(j,t) if using ArrayList and LinkedList.. Thanks!
for (int i =0; i < n; i++){
lst.add(lst.size()/2,3*i);
}
I was thinking that the for loop will take o(n) but I was not clear what what the difference between add(j,t) if using ArrayList and LinkedList.. Thanks!
For inserting in the some slot k of an ArrayList
, finding k is O(1), but then you're going to have to push back each element after k, which is O(n). However, inserting at the end of an ArrayList
is amortized O(1), amortized since we need to factor in the situations when the array needs to be resized.
For a LinkedList
, unless you have a reference to the element at position k, then you need to iterate through the list to find said position, which is O(n), whereas actually inserting is always O(1).
For LinkedList<E>
:
add(int index, E element) is O(n)
For ArrayList<E>
:
add(int index, E element) is O(n - index) amortized, but O(n) worst-case (as above)
Source: