Skip to content
BytePatterns

Drop Nth From End

MediumLinked Lists#fast-slow-pointers#dummy-node~25m

Problem

Given the head of a singly linked list and a number n, remove the node that sits n positions from the end and return the head of the resulting list. Counting starts at the last node, so n equal to 1 removes the tail. You may assume n never exceeds the length of the list, and the goal is a single traversal.

Examples

Input:  head = 1 -> 2 -> 3 -> 4 -> 5, n = 2
Output: 1 -> 2 -> 3 -> 5
Why:    the second node from the end is 4
Input:  head = 1 -> 2, n = 2
Output: 2
Why:    edge case, the removed node is the head itself
Input:  head = 9, n = 1
Output: empty
Why:    edge case, removing the only node empties the list

Hints

0 / 3

Stuck on the idea rather than the code? Fast and Slow Pointers covers it.