PPractick

DSA interview question

Delete All Occurrences of a Key in a Doubly Linked List

Hard · Data structures · Topics: linkedlist, doubly linkedlist

The problem

A playlist stored as a doubly linked list must drop every copy of a song the user has blocked. Copies can be anywhere, including at the head, several in a row, or at the tail, and after each removal both neighbours must be re-linked in both directions. Getting all the cases right in one pass (head removals that move the head, consecutive removals, the tail) is the real test, and the prev pointers make each removal O(1) once you're at the node.

Example: 2 <-> 2 <-> 10 <-> 8 <-> 4 <-> 2 <-> 5 <-> 2, key 2 → 10 <-> 8 <-> 4 <-> 5.

Function signature

DNode* deleteAllOccurrences(DNode* head, int key);  // returns the new head

Test cases

Input (list, key)Output listExplanation
(2 <-> 2 <-> 10 <-> 8 <-> 4 <-> 2 <-> 5 <-> 2, 2)10 <-> 8 <-> 4 <-> 5Head, middle and tail occurrences
(9 <-> 1 <-> 3 <-> 4 <-> 5 <-> 1 <-> 8 <-> 4, 9)1 <-> 3 <-> 4 <-> 5 <-> 1 <-> 8 <-> 4Only the head
(7 <-> 7 <-> 7, 7)(empty)Everything is removed
(1 <-> 2 <-> 3, 5)1 <-> 2 <-> 3Key absent
(empty, 1)(empty)

(Confirm: every node with the key is removed and freed; the backward traversal of the result must be its exact reverse.)

How interviewers phrase it

Clarifying questions to ask

  1. Should the removed nodes be freed?
  2. Can the key appear at the head, consecutively, or at the tail? (Yes, all of these.)
  3. Return the new head?

Follow-ups to expect

  1. "How do you unlink a node?"
  2. "How do you continue after deleting?"
  3. "How is the head updated?"
  4. "How would you do this in a singly linked list?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in