Constant-time list operation — Aptitude Question
Constant-time list operation: A singly linked list is kept with only a head pointer. Which operation runs in O(1)… Answer and worked solution on CodeKairo.
- Topic: Data Structures & Algorithms
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
A singly linked list is kept with only a head pointer. Which operation runs in O(1) time?
Options
- Deleting the last node
- Inserting a node at the front
- Inserting a node at the end
- Searching for a given value
Show the answer and the worked solution
Correct answer: B. Inserting a node at the front
Worked solution
- The head pointer reaches the first node immediately and nothing else.
- Inserting a node at the front means pointing the new node at the old head and moving the head — two assignments, whatever the length.
- Reaching the last node, its predecessor, or a searched value all require walking the list, which is O(n).
Answer: Inserting a node at the front.
The idea
Cost in a linked structure is the number of links you must follow. Keeping a tail pointer as well would make end insertion constant too, but end deletion would still need the predecessor.
Shortcut. With only a head pointer, anything that needs the last node or a search walks n links; only the front needs no traversal.
Common trap. "Inserting a node at the end" is O(1) only when a tail pointer is kept, and this list has just the head.
All Data Structures & Algorithms questions · placement mock tests