19. Remove Nth Node From End of List LeetCode Solution

In this guide we will provide 19. Remove Nth Node From End of List LeetCode Solution with best time and space complexity. The solution to Remove Nth Node From End of List problem is provided in various programming languages like C++, Java and python. This will be helpful for you if you are preparing for placements, hackathon, interviews or practice purposes. The solutions provided here are very easy to follow and with detailed explanations.

Table of Contents

19. Remove Nth Node From End of List LeetCode Solution image

Problem Statement of Remove Nth Node From End of List

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1:

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

Constraints:

The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

Follow up: Could you do this in one pass?

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

19. Remove Nth Node From End of List LeetCode Solution in C++

class Solution {
 public:
  ListNode* removeNthFromEnd(ListNode* head, int n) {
    ListNode* slow = head;
    ListNode* fast = head;

    while (n-- > 0)
      fast = fast->next;
    if (fast == nullptr)
      return head->next;

    while (fast->next != nullptr) {
      slow = slow->next;
      fast = fast->next;
    }
    slow->next = slow->next->next;

    return head;
  }
};
/* code provided by PROGIEZ */

19. Remove Nth Node From End of List LeetCode Solution in Java

class Solution {
  public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode slow = head;
    ListNode fast = head;

    while (n-- > 0)
      fast = fast.next;
    if (fast == null)
      return head.next;

    while (fast.next != null) {
      slow = slow.next;
      fast = fast.next;
    }
    slow.next = slow.next.next;

    return head;
  }
}
// code provided by PROGIEZ

19. Remove Nth Node From End of List LeetCode Solution in Python

class Solution:
  def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
    slow = head
    fast = head

    for _ in range(n):
      fast = fast.next
    if not fast:
      return head.next

    while fast.next:
      slow = slow.next
      fast = fast.next
    slow.next = slow.next.next

    return head
#code by PROGIEZ

Additional Resources

See also  7. Reverse Integer LeetCode Solution

Feel free to give suggestions! Contact Us