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)
.
In array if we see the implementation from C language point of view then it will give us a clear understanding. While we can add and remove elements at constant time in array i.e we don't need to traverse through the entire array Eg: If the array is [1,2,3,4] the 5 can be added directly at Arr[arr.length] postion , similarly we can remove element at constant time ,position to be deleted is Arr[arr.length-1], but let us see a scenario when the array size you have declared is 4 and we want add one more elements then we can clearly see that there is no space for the elements to be added, therefore what we need to do is to make a new array of size lets say double of previous array i.e size 8 , then all the elements of previous array has to be copied here and the new elements is added at 5th position i.e Arr[arr.length] , therefore the insertion time complexity is O(n) as it is directly proportional to number of elements that previous array has.
Now coming to linked list it doesn't have fixed size(it is dynamically allocated at heap memory) declared we can track the first and last position by head and tails pointer therefore irrespective of linkedlist size we need to just change the pointer of head and tail, making time complexity to O(1) ,for adding at last make a new node, change the link part of current tail to this new node address and make this new node as tail.For inserting at first we need to make new node , set the link part of this node as current head address and atlast make this new node as head thus adding a element at 1st position just by altering the one node therefore time complexity will be O(1).