all entries
A-038Day 382026.06.13mediumleetcode #19neetcode150

Remove Nth Node From End of List

#linked-list#two-pointers
leetcode #19 · remove-nth-node-from-end-of-list
01

Problem

· problem
P.038

Remove Nth Node From End of List

leetcode #19

Given the head of a linked list, remove the nth node from the end of the list and return its head.

constraints
  • · The number of nodes in the list is sz: 1 ≤ sz ≤ 30
  • · Node values: 0 ≤ Node.val ≤ 100
  • · n is always valid: 1 ≤ n ≤ sz
// paraphrased summary — see source for full text
examples
example 1input → output
[1,2,3,4,5]
2
[1,2,3,5]
example 2input → output
[1]
1
[]
example 3input → output
[1,2]
1
[1]
02

Pre-solve

· pre-solve
● 1list shown● 2select● 3reveal
  • What if we need to remove the first node in the list?
  • Is the nth node from end 1-indexed or 0-indexed?
  • What distance should be maintained between the two pointers?
  • Can we directly modify the linked list structure?
  • Can we assume the input list is never empty?
  • Can n be greater than the list length?
  • Is a dummy node absolutely necessary?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03

Logic Structure

· logic
● 1slots shown● 2pick per slot● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Create dummy node
dummy = ListNode(0, head)
dummy = ListNode(0)
dummy = head
step 2· Initialize left pointer
left = dummy
left = head
left = None
step 3· Initialize right pointer
right = head
right = dummy
right = head.next
step 4· Advance right pointer by n
right = right.next
right = right.next.next
left = left.next
step 5· Move both pointers together
left = left.next
left = left.next.next
right = right.next
step 6· Remove the target node
left.next = left.next.next
left.next = left.next.next.next
left.next.next = None
step 7· Return the new head
return dummy.next
return head
return left
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04

Solve · Trace

· solve
solution.py
1
class Solution:
2
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
3
        dummy = ListNode(0, head)
4
        left = dummy
5
        right = head
6
7
        while n > 0:
8
            right = right.next
9
            n -= 1
10
11
        while right:
12
            left = left.next
13
            right = right.next
14
15
        # delete
16
        left.next = left.next.next
17
        return dummy.next
mental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[1,2,3,4,5]
2
[1,2,3,5]
case 2
[1]
1
[]
case 3
[1,2]
1
[1]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.