Solution: Remove nth Node from End of List
Let's solve the Remove nth Node from End of List problem using the Two Pointers pattern.
Statement#
Given a singly linked list, remove the node from the end of the list and return its head.
Constraints:
- The number of nodes in the list is
k. -
k -
Node.value -
nk
Solution#
So far, you have probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.
Naive approach#
The naive approach calculates the length of the linked list by traversing the complete list. Then, we set a pointer, say ptr, at the start of the list and move it through the list till it reaches the ptr pointer now points to the node before the target node, i.e., the ptr in a temporary pointer. Relink the ptr node to the node following ptr ’s next node. Delete the node pointed by the temporary pointer. By doing so, the
Optimized approach using two pointers#
Two pointers, left and right, are set at the head node. Move the right pointer n steps forward. After doing that, both pointers are exactly separated by n nodes apart. Start moving both pointers forward until the right pointer reaches the last node. At this point, the left pointer will be pointing to the node before the target node, i.e., the left node to the node following the left’s next node.
If the right pointer reaches NULL while moving it n steps forward, it means that the head node should be removed. We return the head's next node.
Let’s look at the following illustration to get a better understanding of the solution:
1 of 7
2 of 7
3 of 7
4 of 7
5 of 7
6 of 7
7 of 7
Let’s have a look at the code for the algorithm we just discussed.
Solution summary#
- Two pointers,
rightandleft, are set at the head node. - Move the
rightpointernsteps forward. - If
rightreaches NULL, returnhead's next node. - Move both
rightandleftpointers forward tillrightreaches the last node. - Relink the
leftnode to the node atleft's next to the next node. - Return
head.
Time complexity#
The time complexity is , where is the number of nodes in the linked list.
Space complexity#
The space complexity is because we use constant space to store two pointers.
Remove nth Node from End of List
Fast and Slow Pointers: Introduction