Delete all occurrences of a key in DLL
Pattern: Doubly and circular lists
Walk the list, saving next before you touch each node. Every node holding the target unlinks itself through prev and next; if it was the head, the head moves on.
The problem
Given the head of a doubly linked list and a target value, delete every node holding the target and return the head.
For example, 1 ⇄ 2 ⇄ 3 ⇄ 1 ⇄ 4 with target 1 becomes 2 ⇄ 3 ⇄ 4. If every node holds the target, the list becomes
empty.
The function name deleteAllOccurrences matches the takeUforward practice page. Use the link above for the exact
statement and limits. In this guide's code the node type is DNode.
Think first
- When a node is unlinked, how do you keep walking?
- What changes when the head is deleted, perhaps several times in a row?
- Which neighbours' pointers change?
Hints
Brute force, and why it fails
Build a new list of the kept values: O(n) time and O(n) new nodes. Unlinking in place keeps the original nodes.
The key insight
Each node can be removed from where it stands, so one walk deletes every match. Saving next first keeps the walk
going after a deletion.
Dry run
The list is 1 ⇄ 2 ⇄ 3 ⇄ 1 ⇄ 4 and the target is 1.
The plan
cur = head
while cur is not null:
next = cur.next
if cur.val == target:
if cur.prev: cur.prev.next = cur.next else: head = cur.next
if cur.next: cur.next.prev = cur.prev
cur = next
return head
Complexity
- Time
O(n)- Space
O(1)
One walk.
Edge cases
- All nodes match: empty.
- Several matches at the front: the head moves each time.
- Target absent: unchanged.
I've built my logic, show the code
Java
class Solution {
public DNode deleteAllOccurrences(DNode head, int target) {
DNode cur = head;
while (cur != null) {
DNode next = cur.next; // save it before unlinking cur
if (cur.val == target) {
if (cur.prev != null) cur.prev.next = cur.next;
else head = cur.next; // deleting the head
if (cur.next != null) cur.next.prev = cur.prev;
}
cur = next;
}
return head;
}
}C++
class Solution {
public:
DNode* deleteAllOccurrences(DNode* head, int target) {
DNode* cur = head;
while (cur != NULL) {
DNode* next = cur->next; // save it before unlinking cur
if (cur->val == target) {
if (cur->prev != NULL) cur->prev->next = cur->next;
else head = cur->next; // deleting the head
if (cur->next != NULL) cur->next->prev = cur->prev;
}
cur = next;
}
return head;
}
};Python
from lib import DNode
class Solution:
def deleteAllOccurrences(self, head: DNode, target: int) -> DNode:
cur = head
while cur is not None:
nxt = cur.next # save it before unlinking cur
if cur.val == target:
if cur.prev is not None:
cur.prev.next = cur.next
else:
head = cur.next # deleting the head
if cur.next is not None:
cur.next.prev = cur.prev
cur = nxt
return headCommon mistakes
- Moving to
cur.nextafter unlinking without having saved it (in languages where you also clearcur.next). - Forgetting to update the head when it matches.
- Leaving the new head's
prevpointing at a deleted node.