Skip to main content
mediumBlind 75

Remove Nth Node From End of List

Remove nth node from end of linked list Example: [1,2,3,4,5], n = 2 => [1,2,3,5]

Given the head of a singly linked list of integers, remove nodes by their positions counted from the end and return the new head. Part 1 removes the nth node from the end, where n = 1 means the last node and 1 <= n <= the list length. Part 2 accepts an integer array ns and removes all specified positions from the original list at once, counting duplicate positions only once and ignoring positions outside the list. Part 3 performs the Part 1 removal and returns both the new head and the removed integer value. For Parts 1 and 3, the input contains 1 to 30 nodes with values from 0 to 100. Removing every node returns an empty list.

Examples

You write

remove_nth_from_end(head: Optional[ListNode], n: int)

  1. Example 1

    Input
    head = [1,2,3,4,5], n = 2
    returns
    [1,2,3,5]
  2. Example 2

    Input
    head = [1], n = 1
    returns
    []

The pattern behind it

Linked Lists

I reach for it when

  • Nodes point to the next node, and you cannot index into the list.
  • You must reverse, merge, reorder or remove a node.

Say this before you type. Say which pointers you hold and which link you are about to change.

All 12 Linked Lists problems

Two Pointers

I reach for it when

  • The array is sorted, or you can sort it.
  • You need a pair, a triple or a palindrome.

Say this before you type. Say what each pointer means and what a move to the left or right rules out.

All 26 Two Pointers problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Remove Nth Node From End of Listmedium
2Part 2
3Part 3

Each locked part opens in the editor once the part before it passes.

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.