Video in progress
What do index access and inserting in the middle cost in ArrayList and LinkedList?
ArrayList.get(i) is O(1), and inserting in the middle is O(n) because elements are shifted. LinkedList.get(i) is O(n); the insertion itself is O(1), but getting to that spot is O(n) anyway.
📖 Answer
Many people memorize "adding to a LinkedList is fast" and get tripped up right there.
| Operation | ArrayList | LinkedList |
|---|---|---|
get(i) |
O(1) | O(n) |
add at the end |
O(1) amortized | O(1) |
add(i, x) in the middle |
O(n) — shifting | O(n) — search + O(1) linking |
| remove from the front | O(n) | O(1) |
In practice ArrayList is almost always faster. The reason is memory: array elements sit next to each other, which suits the CPU cache. Every LinkedList node is a separate object with two references on top, so it uses more memory and causes more cache misses.
If you need a queue or a stack, take ArrayDeque, not LinkedList. LinkedList pays off only when you do lots of removals from the middle through an iterator, which is rare.
Sign up to mark studied questions and save your progress.