Swap kth-from-end node with head
Company: Amplitude
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's understanding of singly linked list pointer manipulation, in-place node swapping with O(1) extra memory, and handling of edge cases such as when the k-th node from the end is the head.
Constraints
- 1 <= k <= n where n is the list length
- 0 <= n (the list may be empty)
- Node values fit in a 32-bit signed integer
- Only O(1) extra memory may be used
Examples
Input: ([1,2,3,4,5,6], 1)
Expected Output: [6, 2, 3, 4, 5, 1]
Explanation: k=1: the last node (6) swaps with the head (1). Result reads 6,2,3,4,5,1.
Input: ([1,2,3,4,5,6], 2)
Expected Output: [5, 2, 3, 4, 1, 6]
Explanation: k=2: the 2nd-from-end node (5, index n-k=4) swaps with the head (1).
Input: ([1,2,3,4,5,6], 5)
Expected Output: [2, 1, 3, 4, 5, 6]
Explanation: k=5: the 5th-from-end node (2, index n-k=1) swaps with the head (1).
Input: ([1,2,3,4,5,6], 6)
Expected Output: [1, 2, 3, 4, 5, 6]
Explanation: k=6=n: the target node is already the head, so the list is returned unchanged.
Input: ([42], 1)
Expected Output: [42]
Explanation: Single-element list: the head is also the only/last node, so nothing changes.
Input: ([10,20], 1)
Expected Output: [20, 10]
Explanation: Two elements, k=1: the tail (20) swaps with the head (10).
Input: ([10,20], 2)
Expected Output: [10, 20]
Explanation: Two elements, k=2=n: the target is the head, list unchanged.
Input: ([-1,-2,-3,-4], 3)
Expected Output: [-2, -1, -3, -4]
Explanation: k=3, n=4, idx=n-k=1: swap index 0 (-1) with index 1 (-2). Negative values are handled the same way.
Hints
- The k-th node from the end of an n-element list (1-indexed) is at 0-based index n - k. Use the two-pointer technique to reach it in one pass without storing the list.
- Swapping the head with the k-th-from-end node by relinking pointers reorders the chain so that, read head-to-tail, those two nodes trade positions.
- Watch the no-op case: when k == n, n - k == 0, so the target node IS the head and you must return the list unchanged.