← Amplitude Interview Insights
The base case tripped me up more than the main logic.
Use the two-pointer technique to find the K-th node from the end in one pass, then perform the swap by adjusting pointers carefully, handling edge cases like K=1 or K equal to the list length. Ensure O(1) extra memory by only using a few pointer variables and no additional data structures.
Pro tip: Clarify with the interviewer whether K is 1-indexed from the end (i.e., K=1 means the last node) and whether swapping with the head when the K-th node is the head itself should be a no-op. Also, consider drawing the list and pointer movements to avoid mistakes.
Restate the problem to ensure clarity: swap the K-th node from the end with the head. Identify edge cases: empty list, K <= 0, K > length, K=1 (last node), K=length (head itself), and list with only one node.
Use two pointers: move the first pointer K nodes ahead, then move both pointers until the first reaches the end. The second pointer will be at the K-th node from the end. Keep track of the node before it for pointer adjustments.
Handle cases: if K-th node is the head, no swap needed. Otherwise, adjust pointers: set the previous node's next to head, head's next to the K-th node's next, and the K-th node's next to the original second node (or null if K=1). Update the new head to be the K-th node.
After swapping, return the new head, which is the K-th node from the end (unless K equals the length, in which case the head remains the same).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.