Data Structures & Algorithms · Interview question

Can you delete a node from a singly linked list in O(1)?

A strong answer

Not in general, you need the predecessor to rewire its next around the node being deleted, and a singly linked node has no prev, so finding the predecessor is an O(n) walk from the head. Two ways out: use a doubly linked list, where the node holds prev, so you can splice it out in O(1); or, if you only have the node to delete and it's not the tail, use the trick of copying the next node's data into this node and deleting the next node instead, O(1), but it doesn't work for the last node and mangles identity if other pointers reference the next node. So the honest answer is: O(1) deletion of an arbitrary held node requires a doubly linked list (or the copy-next hack with caveats); a plain singly linked list needs O(n) to locate the predecessor.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Linked Lists

Nodes chained by pointers: O(1) splice anywhere, O(n) search and no random access, and how embedded does them without a heap via static node pools and intrusive lists.

More Linked Lists questions

Browse all 472 interview questions
Can you delete a node from a singly linked list in O(1)? | EmbeddedPrep.io