Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of a size() call on a LinkedList in Java?

As the title asks, I wonder if the size() method in the LinkedList class takes amortized O(1) time or O(n) time.

like image 733
Martin Andersson Avatar asked May 14 '09 13:05

Martin Andersson


People also ask

What is the time complexity of LinkedList?

In a singly linked list, the time complexity for inserting and deleting an element from the list is O(n). In a doubly-linked list, the time complexity for inserting and deleting an element is O(1).

Does LinkedList have size method?

LinkedList. size() method is used to get the size of the Linked list or the number of elements present in the linked list. Parameters: This method does not take any parameter. Return Value: This method returns the size or the number of elements present in the LinkedList.

What methods are having complexity O 1 in Java?

For all of the listed methods, we have O(1) for HashMap, LinkedHashMap, IdentityHashMap, WeakHashMap, EnumMap and ConcurrentHashMap.

What is the time complexity for retrieval of data from a LinkedList?

As Linked List elements are not contiguous, each element access incur a Time Complexity of O(√N).


1 Answers

It's O(1). You can google for the source code and you will come to such:

From http://www.docjar.com/html/api/java/util/LinkedList.java.html

All of the Collection classes I have looked at store a the size as a variable and don't iterate through everything to get it.

like image 171
GreenieMeanie Avatar answered Sep 26 '22 00:09

GreenieMeanie