Delete Kth Element of Doubly Linked List
Pattern: Doubly and circular lists
Walk to node k. Link its prev to its next and its next back to its prev; if it was the head, the head moves on.
The problem
Given the head of a doubly linked list and k (counting from 1, with 1 ≤ k ≤ n), delete the k-th node and return the
head. For example, 2 ⇄ 5 ⇄ 7 ⇄ 9 with k = 2 becomes 2 ⇄ 7 ⇄ 9, and with k = 1 becomes 5 ⇄ 7 ⇄ 9.
The function name deleteKthElement 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
- Do you need to stop on node
k - 1here, as in a singly linked list? - Which two pointers change when a middle node goes?
- What changes when it is the head or the tail?
Hints
Brute force, and why it fails
Copy to an array, remove index k - 1, rebuild: O(n) memory. Unlinking in place is O(1) memory.
The key insight
With prev, any node can remove itself: both neighbours are one step away. Only the missing neighbour at either end
needs a check.
Dry run
The list is 2 ⇄ 5 ⇄ 7 ⇄ 9 and k = 2. Walk to node 2, the 5.
The plan
cur = head; repeat k - 1 times: cur = cur.next
if cur.prev is not null: cur.prev.next = cur.next
else: head = cur.next
if cur.next is not null: cur.next.prev = cur.prev
return head
Complexity
- Time
O(k)- Space
O(1)
The walk stops at node k.
Edge cases
k = 1: the head goes, and the new head'sprevbecomes null.k = n: the tail goes.- One node: empty.
I've built my logic, show the code
Java
class Solution {
public DNode deleteKthElement(DNode head, int k) {
DNode cur = head;
for (int i = 1; i < k; i++) cur = cur.next; // node k
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;
return head;
}
}C++
class Solution {
public:
DNode* deleteKthElement(DNode* head, int k) {
DNode* cur = head;
for (int i = 1; i < k; i++) cur = cur->next; // node k
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;
return head;
}
};Python
from lib import DNode
class Solution:
def deleteKthElement(self, head: DNode, k: int) -> DNode:
cur = head
for _ in range(k - 1): # node k
cur = cur.next
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
return headCommon mistakes
- Updating only
next, which leaves the neighbour'sprevpointing at the deleted node. - Forgetting that the new head's
prevmust be null. - Returning the old head after deleting it.