Junior — Middle
What is the asymptotic cost of inserting an element at the beginning of a LinkedList?
sobes.tech AI
Answer from AI
Inserting an element at the beginning of a linked list (LinkedList) has an asymptotic complexity of O(1), meaning it is performed in constant time. This is because adding a new node at the beginning only requires creating a new element and reassigning the head pointer of the list to it, without needing to traverse the entire list.
Example in Java:
LinkedList<Integer> list = new LinkedList<>();
list.addFirst(10); // insertion at the beginning in O(1)