← Amplitude Interview Insights
Use the two-pointer technique to find the K-th node from the end in one pass, then swap it with the head by adjusting pointers. Handle edge cases such as K=1 (swap head with itself) and K equal to the list length (swap head with tail).
Pro tip: Clarify whether K is 1-indexed from the end and whether swapping with the head when K=1 should be a no-op. Also, consider if K is greater than the list length—return the original list or handle as an error.
Confirm that K is 1-indexed from the end, and identify edge cases: empty list, K=1, K=list length, and K > list length.
Use two pointers: move the first pointer K nodes ahead, then move both until the first reaches the end. The second pointer will be at the K-th node from the end.
While moving the second pointer, also keep track of the node before it (prev) to facilitate pointer updates during swap.
Adjust pointers: set prev.next to head, target.next to the original head's next, and update the new head to be the target node. Handle special cases where target is the head or adjacent to head.
After swapping, return the target node as the new head of the list.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.