Swap kth-from-end node with head
AmplitudeSoftware Engineer · Technical ScreenLast updated
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.
Given the head of a singly linked list and an integer k, swap the k-th node from the end with the head node, using O(1) extra memory.
Requirements:
- Perform the swap by changing pointers (swap nodes), not by swapping values.
- Assume
1 <= k <= nwherenis the list length. - If the k-th node from the end is already the head (i.e.,
k == n), return the list unchanged.
Examples (list: 1 -> 2 -> 3 -> 4 -> 5 -> 6):
k = 1=>6 -> 2 -> 3 -> 4 -> 5 -> 1k = 2=>5 -> 2 -> 3 -> 4 -> 1 -> 6k = 5=>2 -> 1 -> 3 -> 4 -> 5 -> 6
Return the new head of the linked list.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.