1st Part :-
I was reading in the book - "Data Structure and Algorithms made easy in Java" that the time complexity for deleting the last element from Linkedlist and Arraylist is O(n). But the Linkedlist internally implements DoublyLinkedlist so the time complexity should be O(1) and similarly for Arraylist as it internally implement Array it should be O(1).
2nd Part :-
It also says that the insertion of an element at the ending of a linkedlist has a time complexity of O(n) but the linkedlist maintains pointers both at the end and at the front. So it this statement correct ? Moreover it says that the time complexity to insert an element in an arraylist at the end is O(1) if array is not full and O(n) if the array is full. Why O(n) if the array is full ?
Thanks for answering the 1st part . Can anyone please also explain the 2nd part. Thanks :)
It depends on what methods you're calling.
A glance at the implementation shows that if you're calling LinkedList.removeLast()
, that's O(1). The LinkedList maintains pointers both to the first and last node in the list. So it doesn't have to traverse the list to get to the last node.
Calling LinkedList.remove(index)
with the index of the last element is also O(1), because it traverses the list from the closest end. [Noted by user @andreas in comment below.]
But if you're calling LinkedList.remove(Object)
, then there's an O(n) search for the first matching node.
Similarly, for ArrayList, if you're calling ArrayList.remove(index)
with the index of the last element, then that's O(1). For all other indices, there's a System.arrayCopy()
call that can be O(n) -- but that's skipped entirely for the last element.
But if you call ArrayList.remove(Object)
, then again there's an O(n) search for the first matching node.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With