Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Complexity for Java ArrayList

I found other entries for this question that dealt with specific methods, but nothing comprehensive. I'd like to verify my own understanding of the most often used methods of this data structure:

O(1) - Constant Time:

isEmpty() add(x) add(x, i) set(x, i) size() get(i) remove(i) 

O(N) - Linear Time:

indexof(x) clear() remove(x) remove(i) 

Is this correct? Thanks for your help.

like image 460
dvanaria Avatar asked Jun 30 '11 20:06

dvanaria


People also ask

What is the time complexity of ArrayList contains?

Getting back to complexity analysis, the ArrayList. contains() method requires O(n) time. So the time we spend to find a specific object here depends on the number of items we have in the array.

Is ArrayList O of N?

To remove an element by value in ArrayList and LinkedList we need to iterate through each element to reach that index and then remove that value. This operation is of O(N) complexity.

What is the time complexity of ArrayList and LinkedList?

ArrayList has O(1) time complexity to access elements via the get and set methods. LinkedList has O(n/2) time complexity to access the elements.

What is the time complexity of appending an element to an ArrayList Java?

TIL that the amortized time complexity of adding an item to an ArrayList in Java is O(1), but that the “worst case” for an add operation is O(n).


1 Answers

The best resource is straight from the official API:

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

like image 121
brian_d Avatar answered Sep 29 '22 03:09

brian_d