MediumNo. 0019

Remove Nth Node From End of List — LeetCode 19 Python Solution

Topics
Linked List, Two Pointers
Reading time
3 min

The problem

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

Example

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

Python solution

PythonSolution
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(next=head)
        fast = slow = dummy
        for _ in range(n):
            fast = fast.next
        while fast.next:
            slow, fast = slow.next, fast.next
        slow.next = slow.next.next
        return dummy.next

Complexity

Time
O(n)where n is the length of the linked list
Space · auxiliary
O(1)

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 19. Remove Nth Node From End of List is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0061Rotate ListMedium
0082Remove Duplicates from Sorted List IIMedium
0086Partition ListMedium
0148Sort ListMedium
0876Middle of the Linked ListEasy
1721Swapping Nodes in a Linked ListMedium

Frequently asked questions

How hard is LeetCode 19. Remove Nth Node From End of List?

LeetCode 19. Remove Nth Node From End of List is rated Medium on LeetCode.

What is the time complexity of LeetCode 19. Remove Nth Node From End of List?

The Python solution on this page runs in O(n), where n is the length of the linked list.

What is the space complexity of LeetCode 19. Remove Nth Node From End of List?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 19. Remove Nth Node From End of List cover?

LeetCode 19. Remove Nth Node From End of List is tagged Linked List and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.