InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Remove Nth Node From End of List

medium Original ↗ 00:00

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 handling for n out of range 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 reaches the end?
Hint 3 Start with a dummy node before the head. Advance the fast pointer n steps from the head, then move both until fast reaches the end. Slow now sits just before the target node, and the dummy handles the case where the head is deleted.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug