Deletion of the Kth element of Linked List
Pattern: Traversal and dummy nodes
To delete node k, stand on node k - 1 and skip over it. Deleting the head (k = 1) just returns the second node.
The problem
Given the head of a singly linked list and a position k (counting from 1, with 1 ≤ k ≤ n), delete the k-th node and
return the head. For example, 3 → 4 → 5 with k = 2 becomes 3 → 5, and with k = 1 becomes 4 → 5.
The function name deleteKthNode matches the takeUforward practice page. Use the link above for the exact statement
and limits.
Think first
- Which node's pointer changes when node
kis removed? - How many steps from the head reach node
k - 1? - What is different when
k = 1?
Hints
Brute force, and why it fails
Copy to an array, remove index k - 1, and rebuild: O(n) memory. Walking to node k - 1 needs O(1) memory.
The key insight
Deleting is always done from the node before. The only position without a node before it is the head, which is why
k = 1 is the special case.
Dry run
The list is 3 → 4 → 5 and k = 2. Node 2 is the 4, so stand on node 1, the 3.
The plan
if k == 1: return head.next
prev = head
repeat k - 2 times: prev = prev.next
prev.next = prev.next.next
return head
Complexity
- Time
O(k)- Space
O(1)
The walk stops at node k - 1.
Edge cases
k = 1: the head is removed.k = n: the tail is removed.- One node with
k = 1: the result is empty.
I've built my logic, show the code
Java
class Solution {
public ListNode deleteKthNode(ListNode head, int k) {
if (k == 1) return head.next; // removing the head: the second node becomes the head
ListNode prev = head;
for (int i = 1; i < k - 1; i++) prev = prev.next; // walk to node k - 1
prev.next = prev.next.next; // skip over node k
return head;
}
}C++
class Solution {
public:
ListNode* deleteKthNode(ListNode* head, int k) {
if (k == 1) return head->next; // removing the head: the second node becomes the head
ListNode* prev = head;
for (int i = 1; i < k - 1; i++) prev = prev->next; // walk to node k - 1
prev->next = prev->next->next; // skip over node k
return head;
}
};Python
from lib import ListNode
class Solution:
def deleteKthNode(self, head: ListNode, k: int) -> ListNode:
if k == 1:
return head.next # removing the head: the second node becomes the head
prev = head
for _ in range(k - 2): # walk to node k - 1
prev = prev.next
prev.next = prev.next.next # skip over node k
return headCommon mistakes
- Walking
k - 1steps, which lands on nodekinstead of the one before it. - Treating
kas 0-based. - Returning
headafter deleting the head.