Remove Nth Node From End of List: the idea to remember.
Remove the nth node counted from the end of a linked list, with n guaranteed valid.
The core insight
Start from a dummy head, move fast n nodes ahead, and move both pointers until fast reaches the last node.
Why it works
The fixed gap makes slow stop immediately before the node to delete. A dummy predecessor handles removal of the head uniformly.
The mistake to avoid
Return dummy.next because the original head might be removed. The loop condition depends on the exact initial gap.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0); dummy.next = head;
ListNode slow = dummy, fast = dummy;
for (int i = 0; i < n; i++) fast = fast.next;
while (fast.next != null) { slow = slow.next; fast = fast.next; }
slow.next = slow.next.next;
return dummy.next;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.