VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-nth-node-from-end-of-the-linked-list/

⇱ Remove Nth node from end of the Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove Nth node from end of the Linked List

Last Updated : 4 Sep, 2024

Given a linked list. The task is to remove the Nth node from the end of the linked list.

Examples:

Input : LinkedList = 1 ->2 ->3 ->4 ->5 , N = 2
Output : 1 ->2 ->3 ->5
Explanation: Linked list after deleting the 2nd node from last which is 4, is 1 ->2 ->3 ->5

👁 2


Input : LinkedList = 7 ->8 ->4 ->3 ->2 , N = 1 
Output : 7 ->8 ->4 ->3  
Explanation: Linked list after deleting the 1st node from last which is 2, is 7 ->8 ->4 ->3  

👁 1

[Expected Approach - 1] Find Equivalent node from Front - O(n) Time and O(1) Space:

To remove the Nth node from the end, first determine the length of the linked list. Then, delete the (length - N + 1)th node from the front.

Follow the steps below to solve the problem:

  • Traverse the linked list to calculate its length.
  • Compute the position to delete from the front : nodeToDelete = (length - N + 1).
  • If nodeToDelete is 1, update the head to the next of head node.
  • Traverse to the (target - 1)th node and update its next pointer to skip the target node.
  • Return the modified linked list.

Below is the implementation of the above approach: 


Output
 1 2 3 5

Time Complexity: O(2n), due to traversing the list twice (once for length calculation and once for node removal).
Auxiliary Space: O(1).

[Expected Approach - 2] Using Fast and Slow Pointer - O(n) Time and O(1) Space:

The idea is to first move the fast pointer N steps ahead, then move both fast and slow pointers together until fast reaches the end. The slow pointer will then be just before the node to be removed, allowing to update the next pointer to skip the target node.

Below is the implementation of the above approach:


Output
 1 2 3 5

Time complexity: O(n), due to a single pass through the list with the two pointers.
Space complexity: O(1).

Comment
Article Tags: