InterviewPrepKit

Home / Coding / Linked List

Remove Nth Node From End of List

medium Original β†—
Solving tips
  • For the single-pass solution, use two pointers kept exactly n apart: when the fast one runs off the end, the slow one is at the victim's predecessor.
  • Start slow at a dummy node and fast at the head, then advance fast n steps first; the dummy makes head deletion a non-special case.
  • The key off-by-one: you want slow to land on the predecessor, not the victim, so mind exactly where each pointer starts and where fast stops.
  • Target O(sz) time in one pass with O(1) space; return dummy.next, never head.

Problem

Given the head of a singly linked list and an integer n, delete the node that sits n positions from the end of the list (so n = 1 means the last node), and return the head of the modified list.

The follow-up asks: can you do it in a single pass over the list?

Examples

  • Input: head = [1, 2, 3, 4, 5], n = 2 β†’ Output: [1, 2, 3, 5] The 2nd node from the end is 4; it is removed.
  • Input: head = [1], n = 1 β†’ Output: [] The only node is also the 1st from the end; removing it empties the list.
  • Input: head = [1, 2], n = 2 β†’ Output: [2] The 2nd from the end is the head itself.

Constraints

  • 1 <= sz <= 30 where sz is the number of nodes, and 1 <= n <= sz.
  • 0 <= Node.val <= 100.
  • n is always valid, so no β€œn too large” handling is needed β€” but the deleted node can be the head.

Think about it first

Hint 1 "n from the end" is the same as "(length βˆ’ n + 1) from the start". What is the simplest way to get the length?
Hint 2 For one pass: if two pointers walk together while staying exactly n nodes apart, where is the trailing pointer when the leading one falls off the end?
Hint 3 Start both pointers at a dummy node before the head. Advance the fast pointer n+1 steps... or more simply: advance fast n steps, then move both until fast reaches the last node β€” slow now sits just *before* the victim, and the dummy handles head deletion.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.