Algorithm-Day30-Remove-Nth-Node-From-End-of-List-lc-19
π§© Problem Description
Given the head of a linked list, remove the n-th node from the end of the list and return its head.
π¬ Example
1 | Input: head = [1,2,3,4,5], n = 2 |
π‘ Intuition
Use the two-pointer technique:
- Move
firstpointernsteps ahead. - Then move both
firstandsecondtogether untilfirstreaches the end. - Now
secondis just before the node to delete.
β Trick: use a dummy node before head to simplify edge cases like deleting the head.
π’ Java Code
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(L), where L is the length of the list
- Space Complexity: O(1)
βοΈ Summary
- Two-pointer pattern is super useful for problems involving relative positions.
- Using a dummy node helps avoid corner-case bugs when deleting the head.
- This technique appears frequently β make sure youβre confident with it.
Similar problems include:
lc-876: Middle of the Linked Listlc-160: Intersection of Two Linked Listslc-234: Palindrome Linked List