Problem statement:
Given the head of a linked list, and an integer k. remove the kth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5,6], k=2 Output: [1,2,3,4,6]
Example 2:
Input: head = [3], k=1 Output: []
Algorithmic Steps This problem is solved with the help of two pointers approach and maintaining a dummy node. The algorithmic approach can be summarized as follows:
-
Accept the
headnode of the linkedlist and an integerkto represent node position from end of the list. -
Create a
dummynode to cover the edge cases such as list with a single node, and also finding a node before the removed node. -
Connect dummy node to head node of the list.
-
Create two pointers named
firstandsecond, which are pointed to dummy and head nodes. -
Loop over the list
knumber of times and update thesecondpointer to next node for each iteration. -
Loop over the list again until
secondpointer is not equal to null. -
Update both
firstandsecondpointerq to their next node for each iteration of previous loop. Once the loop ends, thefirstpointer sits at the node just before the removed node. -
Skip the removed node by connecting the node of first pointer with the node after the removed node.
-
Return the next node of dummy node which represents the new head node of modified list.
Time and Space complexity:
This algorithm takes a time complexity of O(n), where n is the number of nodes in the list head and k represents the node from the last. This is because we need to traverse each node in the list.
Here, we don't use any additional datastructure other than few pointer variables. Hence, the space complexity will be O(1).
