← Amplitude Interview Insights
My first instinct was to just swap the values and call it done, but they explicitly said no value swapping, pointer changes only.
Use the two-pointer technique to find the k-th node from the end in one pass: advance a fast pointer k steps ahead, then move both pointers until fast reaches the end. Then swap the target node with the head by carefully updating pointers, handling edge cases like k=1 (target is head) and k=n (target is last node).
Pro tip: Before writing code, clarify edge cases with the interviewer: what if k is larger than the list length? What if k=1? Also, consider using a dummy node to simplify pointer manipulation when the target is adjacent to the head.
Ask about k's validity (e.g., k <= length), and discuss cases like empty list, k=1, k=length, and adjacent nodes. This shows thoroughness and avoids incorrect assumptions.
Use two pointers: move fast k steps ahead, then move both until fast reaches the last node. The slow pointer will point to the k-th node from the end. Keep track of the node before slow (prev) for pointer updates.
If the target is the head (k=length), no swap is needed; return head. If the target is the node right after head, update pointers carefully to avoid cycles.
Detach the target node and the head, then re-link: set prev.next to head, target.next to head.next, and update the new head to target. Ensure no cycles and correct linkage.
Return the target node as the new head. Walk through the list mentally or with a small example to confirm the swap is correct and no nodes are lost.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.