DSA AnimatorREVISION VIDEOS
← Back to problems
New

Remove Nth Node From End of List — LeetCode 19 video explanation

Remove the n-th node from the end of the list. Return the head, ideally in one pass.

Loading videos…

DSA Animator › DSA Revision › Linked List › Remove Nth Node From End of List

Key moments in the Remove Nth Node From End of List video

0:04Problem0:10Example0:15Brute force0:23Key idea0:35Dry run0:48Code1:05Takeaway

What you will learn

Remember: a gap of n between two pointers finds the n-th from the end. A dummy head removes the edge case of deleting the first node. The video solves Remove Nth Node From End of List (LeetCode 19, Medium) with the Two Pointers with Gap pattern from the Linked List topic, and you can replay every step in the interactive Remove Nth Node From End of List animation.

Remove Nth Node From End of List video transcript

Problem

Remove the n-th node from the end of the list. Return the head, ideally in one pass.

Example

For 1, 2, 3, 4, 5 with n equal to 2, remove 4, giving 1, 2, 3, 5.

Brute force

Counting the length, then walking to length minus n, takes two passes. A fixed gap between two pointers does it in one.

Key idea

Add a dummy node before the head, so removing the head is not a special case. Move fast n plus 1 steps ahead of slow. Then move both until fast falls off the end, and slow sits just before the target.

Dry run

Slow and fast start at the dummy. Fast moves 3 steps ahead, to node 3. Both move together until fast is null, and slow stops at 3. Link 3 straight to 5, skipping 4. The list is 1, 2, 3, 5.

Code

In code, create a dummy pointing at head, and start both pointers there. Move fast n plus 1 times, then move both until fast is null. Set slow dot next to slow dot next dot next, and return dummy dot next, so it's one pass and O of 1 space.

Takeaway

Remember: a gap of n between two pointers finds the n-th from the end. A dummy head removes the edge case of deleting the first node.

More Linked List revision videos

← All 185 DSA revision videos