# What is the average time complexity, for a single linked list, for performing an insert?

I thought this would be a very simple O(n) b.c. you can do the insert any where with in the list.

The longer the list, the longer it will take on average to do the insert.

However according to bigocheatsheet it is O(1) or has no dependency on the size of the list.

What is wrong here?

• Insertion != ordered insertion. That said, the cheat sheet does seem to be inconsistent with what the operations mean. You should contact the author.
– Raphael
Oct 20 '15 at 18:58
• @Raphael, you certainly can insert in constant time at the beginning of the list. Oct 20 '15 at 19:55
• @vonbrand Right. Also anywhere, if you have a pointer to a neighbour.
– Raphael
Oct 20 '15 at 20:05

Either if you want to insert at the end of the list or at the beginning of the list, you're going to have $O(1)$ Complexity for that and $O(1)$ space. If you want to insert at the beginning of the list, you just make the new list head the node you want to insert, and link it to the previous list head. If you want to insert at the end of the list, you can also hold the end of the list as a pointer and insert a new node after it. If you want to insert in an arbitrary place in the list, then linearly going there is going to be the best you can do ( to my knowledge ). Statistically you'll have to go through $(n+1)/2$ nodes to get through yours.

• So the issue was that the chart on the link I posted did not specify. For time complexity it is O(1) for inserting at the beginning or end and O(n) for inserting at some arbitrary point in between. Oct 9 '15 at 17:24
• same question addressed here - stackoverflow.com/questions/840648/…
– Abhi
Jan 24 '20 at 11:16

If you have no additional requirements on the contents of the list, you can just insert the item at the head, which is O(1).

If you do (e.g. the list must be kept sorted or deduplicated), insertion is more expensive.

https://www.bigocheatsheet.com considering finding (Access) the position of the element before insert as separate operation.

Array:

• Access - O(1) // we can get the element by index directly
• Insertion - O(n) // in the worst case we need to resize the array to have a space for the new element