The Swapping Nodes in a Linked List interview question asks you to swap the values of the k-th node from the beginning and the k-th node from the end of a linked list. For example, if the list is 1 -> 2 -> 3 -> 4 -> 5 and k = 2, the 2nd node from the beginning is 2 and the 2nd node from the end is 4. After swapping their values, the list becomes 1 -> 4 -> 3 -> 2 -> 5.
This "Medium" problem is frequently asked by Microsoft, Amazon, and Google. It tests your proficiency with linked list traversal and the two-pointer technique (specifically the "slow and fast pointer" or "fixed distance pointer" strategy). It's a great way to see if a candidate can find the k-th node from the end in a single pass without first calculating the total length of the list.
The primary pattern is the Two Pointers or Fast/Slow Pointer interview pattern.
first k-1 times from the head.second. Start second at the head and a temporary pointer temp at first. Move both temp and second until temp reaches the last node. second will now be at the k-th node from the end.first and second.List: [10, 20, 30, 40, 50, 60], k = 2.
first moves to the 2nd node: 20.temp starts at first (20), second starts at head (10).temp and second together:
temp -> 30, second -> 20temp -> 40, second -> 30temp -> 50, second -> 40temp -> 60 (tail), second -> 50.second is at 50. Swap values of first (20) and second (50).
Result: [10, 50, 30, 40, 20, 60].A common error is confusing 1-based and 0-based indexing for k. Another mistake is thinking you must swap the nodes themselves (which involves updating four pointers) when the problem only asks to swap the values. While swapping nodes is more challenging and might be asked as a follow-up, swapping values is the standard requirement.
When preparing for the Swapping Nodes in a Linked List coding problem, practice finding the "k-th from end" in one pass. It’s a foundational linked list skill. Also, remember that while swapping values is easier, in a real-world scenario with large objects, swapping the pointers (nodes) is often more efficient than copying the data.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Remove Duplicates from Sorted List II | Medium | Solve | |
| Partition List | Medium | Solve | |
| Rotate List | Medium | Solve | |
| Delete the Middle Node of a Linked List | Medium | Solve | |
| Remove Nth Node From End of List | Medium | Solve |