Talentd
FleetCode

19. Remove Nth Node From End of List

Medium52.4% acceptance18 companies

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?

Hints open one at a time

Hint 1
Maintain two pointers and update one with a delay of n steps.
7:09
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1# Definition for singly-linked list.
2# class ListNode:
3# def __init__(self, val=0, next=None):
4# self.val = val
5# self.next = next
6class Solution:
7 def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
8
Starter codePython 3Spaces: 4
Examples
Input
[1,2,3,4,5]
2
Input
[1]
1
Input
[1,2]
1
Your code is saved on this device.Solution