What is the complexity of inserting at the end of a list?
The complexity of inserting at the end of a linked list depends on whether a pointer to the last element (tail) is stored.
1. If there is no tail
(only head - as in a simple singly linked list)
To add a new element at the end, you need to:
- Start at
head; - Walk through all nodes until you find the last one (
next = None); - Add a new node and link it.
This requires walking through the entire list - Complexity: O(n).
2. If tail is stored separately
(the list structure holds both pointers: head and tail)
Then:
- A new node is created;
- The current
tail.nextpoints to it; tailis updated to the new node.
Everything is done in constant time - Complexity: O(1).
3. For a doubly linked list
The same logic applies:
- without
tail- O(n); - with
tail- O(1).
Comparison with an array
| Structure | Insertion at the end |
|---|---|
| Array (dynamic) | amortized O(1), but sometimes O(n) on resizing |
Linked list with tail | O(1) |
Linked list without tail | O(n) |
Summary:
Insertion at the end of a linked list is: • O(1), if there is a
tailpointer, • O(n), if you need to walk through the entire list to reach the end.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.