Tutorialspoint
Problem
Solution
Submissions

Remove Nth Node

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program to remove the nth node from the end of a linked list and return its head. Given a linked list, remove the n-th node from the end of the list and return the modified list's head.

Example 1
  • Input: head = [1, 2, 3, 4, 5], n = 2
  • Output: [1, 2, 3, 5]
  • Explanation: The linked list is 1->2->3->4->5. We need to remove the 2nd node from the end, which is 4. After removal, the linked list becomes 1->2->3->5.
Example 2
  • Input: head = [1], n = 1
  • Output: []
  • Explanation: The linked list only has one node: 1. We need to remove the 1st node from the end, which is the only node. After removal, the linked list is empty.
Constraints
  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz
  • Time Complexity: O(L) where L is the length of the list
  • Space Complexity: O(1)
ArraysNumberFacebookHCL Technologies
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the two-pointer technique with a fast and slow pointer
  • Move the fast pointer n steps ahead first
  • Then move both pointers together until the fast pointer reaches the end
  • At this point, the slow pointer will be just before the node to be removed
  • Update the next pointer of the slow pointer to skip the node to be removed

Steps to solve by this approach:

 Step 1: Create a dummy node that points to the head to handle edge cases like removing the head node.
 Step 2: Use two pointers, fast and slow, both initially pointing to the dummy node.
 Step 3: Move the fast pointer n+1 steps ahead.
 Step 4: Move both fast and slow pointers one step at a time until the fast pointer reaches the end of the list.
 Step 5: At this point, the slow pointer will be pointing to the node just before the one to be removed.
 Step 6: Update the next pointer of the slow pointer to skip the node to be removed.
 Step 7: Return the next pointer of the dummy node, which is the new head of the list.

Submitted Code :