It is said that the complexity of the LinkedList remove and the add operation is of O(1)
. and in case of ArrayList
it is of O(n)
.
Remove and the add operations are said to be of O(1) in case of
LinkedList
as, inLinkedList
the shift is not involved, but there is traverse operation involved right?
Adding to either end of a linked list does not require a traversal, as long as you keep a reference to both ends of the list. This is what Java does for its add and addFirst/addLast methods.
Same goes for parameterless remove and removeFirst/removeLast methods - they operate on list ends.
remove(int) and remove(Object) operations, on the other hand, are not O(1). They requires traversal, so you correctly identified their costs as O(n).