Skip to the solution
MediumDSA9 min read

How do you remove the nth node from the end of a linked list?

930 views

The problem

Question presented to candidate: "Given the head of a singly linked list, remove the nth node from the end and return the head. For 1, 2, 3, 4, 5 and n = 2 the answer is 1, 2, 3, 5. Can you do it in one pass? Please write it in Python."

What a strong answer should cover:

  • The two-pass baseline: count the length, then unlink the node at index length - n.
  • The one-pass version: a dummy node, fast moved n + 1 links ahead, then both pointers move until fast is None; slow is the predecessor of the target.
  • Why the dummy node matters: removing the head (n = length) needs no special case.
  • O(L) time and O(1) space for both, and an honest note that "one pass" does not mean fewer pointer moves.
  • Python specifics: ListNode(0, head) as the dummy, for _ in range(n + 1), and the unlinked node is reclaimed by the garbage collector once nothing refers to it.

Clarifying questions expected:

  • "Is n 1-based and always between 1 and the length?"
  • "Should I return the new head?"

Code / implementation expected: Yes โ€” remove_nth_from_end(head, n) in Python, one pass.

  • linked-list
  • two-pointers

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonOne-pass removal with a dummy node, including the edge cases
PythonOne pass versus two passes: same results, and the pointer moves counted

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 53 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you solve the Combination Sum problem?

Continue