Exchange List Head With kth-Last Node
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given the head of a singly linked list of length n together with a 1-based integer k. Rearrange the list so that the head node and the k-th node counted from the tail trade positions, and return the resulting list's head.
Your implementation must obey these rules:
- Rewire links, not payloads: Relocate the actual
ListNodeinstances by updating.nextreferences rather than copying or swapping.valattributes. - Constant auxiliary space: The pointer-swapping routine itself may only allocate
O(1)extra memory (a fixed number of pointer variables, with no auxiliary arrays or call-stack recursion). - Counting from the tail:
k = 1refers to the last node in the chain,k = 2refers to the second-to-last node, andk = nrefers to the current head node. - No-op when identical: Whenever
k == n, the target node is already at the front of the list, so the list remains as-is.
For automated evaluation, implement swap_kth_from_end_with_head(values: List[int], k: int) -> List[int], which builds a singly linked list from values, performs the O(1)-space node exchange, and returns the resulting node values from head to tail.
Examples
Example 1
Input: values = [10, 20, 30, 40, 50], k = 1
Output: [50, 20, 30, 40, 10]
Explanation: Counting k = 1 node from the end selects the tail node (50). Detaching 50 and exchanging its links with the original head (10) places 50 at the front and 10 at the end, leaving the middle chain 20 -> 30 -> 40 untouched.
Example 2
Input: values = [7, 14, 21, 28, 35], k = 2
Output: [28, 14, 21, 7, 35]
Explanation: In a 5-node list, the 2nd node from the tail holds 28. Rewiring pointers moves 28 ahead of 14 as the new head and splices 7 between 21 and 35.
Example 3
Input: values = [4, 8, 12, 16], k = 3
Output: [8, 4, 12, 16]
Explanation: In a 4-node list, counting k = 3 from the tail lands on 8, which sits directly after the head 4. Redirecting their .next pointers swaps the adjacent pair to produce 8 -> 4 -> 12 -> 16.
Constraints
1 <= n <= 10^5, wheren = len(values)1 <= k <= n-10^9 <= values[i] <= 10^9- The linked-list swap itself must run in
O(n)time andO(1)extra space.
Step-by-step walkthrough
Restate the problem
We receive a singly linked list containing
nnodes and a 1-based countk(1 <= k <= n), and we need to exchange the first node (head) with thek-th node counted from the back, returning the updated head node:- Counting from the tail is 1-indexed:
k = 1selects the last node (0-based positionn - 1),k = 2selects the penultimate node (n - 2), andk = nselectsheaditself (0). - Rewire
.nextreferences directly instead of mutating.valpayloads on existing nodes. - Keep auxiliary space to
O(1)during the swap (only a constant handful of pointer variables, with no node arrays or recursion). - Whenever
k == n, the target node is already at the front, so nothing changes.
Because the test harness passes
values: List[int]and expects aList[int]back, our entry function constructs a linked list, executes theO(1)-space pointer exchange, and collects the resulting sequence of node values.- Counting from the tail is 1-indexed:
Why array indexing and value swapping break the rules
A naive attempt pushes every node into a Python list and swaps
.valattributes:def forbidden_shortcut(head, k): nodes = [] current = head while current is not None: nodes.append(current) current = current.next target = nodes[len(nodes) - k] head.val, target.val = target.val, head.val # forbidden: mutates .val! return headThat violates both core constraints:
nodesconsumesO(n)auxiliary memory, and overwriting.valcorrupts callers holding external references to specificListNodeobjects.To physically relocate
targetto the front and placeheadintotarget's former position in a one-way chain, we need references to bothtargetandprev_target(the predecessor node whose.nextlink must now point tohead).Locate target and prev_target in O(1) memory with a fixed-gap ruler
Think of placing a rigid spacer of width
kat the front of the list:targetstarts onhead(index0) whilefaststepsknodes forward to indexk. Next, advance both pointers in lockstep one node at a time untilfastwalks off the tail ontoNone(indexn). Because their separation stays fixed atk,targetstops on indexn - kwhileprev_targettrails one node behind atn - k - 1:Example 2: 7 -> 14 -> 21 -> 28 -> 35 -> None, k = 2 (n = 5, want index 3 = node 28) Step A — Advance `fast` k = 2 steps ahead of `target`: 7 -> 14 -> 21 -> 28 -> 35 -> None ▲ ▲ target fast (prev_target = None) Step B — Slide together 3 steps until `fast` reaches None: 7 -> 14 -> 21 -> 28 -> 35 -> None ▲ ▲ ▲ prev_target target fast# Phase 1: Advance `fast` k steps ahead of `head` to form a fixed gap of length k. fast: Optional[ListNode] = head for _ in range(k): assert fast is not None fast = fast.next # Slide `fast` and `target` together until `fast` hits None (index n); # `target` lands on index n - k (k-th from end) and `prev_target` trails by 1. prev_target: Optional[ListNode] = None target: ListNode = head while fast is not None: prev_target = target assert target.next is not None target = target.next fast = fast.nextSketch all three pointer-swap configurations first
Before modifying any
.nextattribute, map out the three distinct layouts oftargetrelative tohead:Case 1: Target IS head (k == n, prev_target is None) [head/target] -> ... ==> return head as-is Case 2: Target sits immediately after head (k == n - 1, prev_target is head) Before: [head] ──► [target] ──► [after_target] After: [target] ──► [head] ──► [after_target] Case 3: One or more nodes sit between head and target (1 <= k <= n - 2) Before: [head] ──► [after_head] ... [prev_target] ──► [target] ──► [after_target] After: [target] ──► [after_head] ... [prev_target] ──► [head] ──► [after_target]Why does Case 2 require its own
ifbranch? Wheneverheadandtargetare neighbors,after_head(head.next) istargetitself! Running Case 3's assignmenttarget.next = after_headwould executetarget.next = target, creating an infinite self-loop.Code the in-place pointer swap
Store
after_target = target.nextand (for Case 3)after_head = head.nextin local variables before mutating any.nextreference. Capturing both neighbors up front also handles the 3-node tail exchange (10 -> 20 -> 30,k = 1, whereafter_headandprev_targetboth point to20) seamlessly:30.next = 20,20.next = 10,10.next = None.def swap_head_with_kth_from_end(head: ListNode, k: int) -> ListNode: # Phase 1: Advance `fast` k steps ahead of `head` to form a fixed gap of length k. fast: Optional[ListNode] = head for _ in range(k): assert fast is not None fast = fast.next # Slide `fast` and `target` together until `fast` hits None (index n); # `target` lands on index n - k (k-th from end) and `prev_target` trails by 1. prev_target: Optional[ListNode] = None target: ListNode = head while fast is not None: prev_target = target assert target.next is not None target = target.next fast = fast.next # Case 1 (k == n): `target` is already `head`, so no pointers need to change. if prev_target is None: return head # Save `target.next` before overwriting any `.next` pointers. after_target = target.next # Case 2 (k == n - 1): `head` and `target` are adjacent (head -> target -> after_target). # Must be handled separately: in the general formula, `after_head` would equal `target`, # so `target.next = after_head` would point `target` to itself and create a cycle! if prev_target is head: target.next = head head.next = after_target return target # Case 3 (general, >= 1 node between them): # head -> after_head ... prev_target -> target -> after_target # becomes target -> after_head ... prev_target -> head -> after_target. after_head = head.next target.next = after_head prev_target.next = head head.next = after_target return targetCode the list conversion helpers and judge wrapper
build_listattaches nodes onto a dummy sentinel so the loop body has no empty-list special case, whileto_valueswalks fromnew_headuntilNoneto serialize the final node order.class ListNode: def __init__(self, val: int, next: "Optional[ListNode]" = None): # Singly linked list node holding a payload `val` and forward pointer `next`. self.val = val self.next = next def build_list(values: List[int]) -> Optional[ListNode]: # Dummy sentinel head lets us append every node uniformly without an empty-list branch. dummy = ListNode(0) tail = dummy for value in values: tail.next = ListNode(value) tail = tail.next return dummy.next def to_values(head: Optional[ListNode]) -> List[int]: # Read values out of the linked list from head to None for the judge output. values: List[int] = [] current = head while current is not None: values.append(current.val) current = current.next return values def swap_kth_from_end_with_head(values: List[int], k: int) -> List[int]: head = build_list(values) if head is None: return [] new_head = swap_head_with_kth_from_end(head, k) return to_values(new_head)Walk through Examples 2 and 3
Let's trace both non-adjacent and adjacent exchanges on our sample cases:
Example 2: 7 -> 14 -> 21 -> 28 -> 35 (n = 5, k = 2) 1. Advance fast 2 steps: fast = 21, target = 7, prev_target = None 2. Slide 3 steps until fast is None: prev_target = 21, target = 28, after_target = 35, after_head = 14 3. Case 3 (prev_target = 21 is neither None nor head): 28.next = 14, 21.next = 7, 7.next = 35 4. Resulting chain from target (28): 28 -> 14 -> 21 -> 7 -> 35 Example 3: 4 -> 8 -> 12 -> 16 (n = 4, k = 3) 1. Advance fast 3 steps: fast = 16, target = 4, prev_target = None 2. Slide 1 step until fast is None: prev_target = 4 (head!), target = 8, after_target = 12 3. Case 2 (prev_target is head): 8.next = 4, 4.next = 12 4. Resulting chain from target (8): 8 -> 4 -> 12 -> 16Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class ListNode: def __init__(self, val: int, next: "Optional[ListNode]" = None): # Singly linked list node holding a payload `val` and forward pointer `next`. self.val = val self.next = next def build_list(values: List[int]) -> Optional[ListNode]: # Dummy sentinel head lets us append every node uniformly without an empty-list branch. dummy = ListNode(0) tail = dummy for value in values: tail.next = ListNode(value) tail = tail.next return dummy.next def to_values(head: Optional[ListNode]) -> List[int]: # Read values out of the linked list from head to None for the judge output. values: List[int] = [] current = head while current is not None: values.append(current.val) current = current.next return values def swap_head_with_kth_from_end(head: ListNode, k: int) -> ListNode: # Phase 1: Advance `fast` k steps ahead of `head` to form a fixed gap of length k. fast: Optional[ListNode] = head for _ in range(k): assert fast is not None fast = fast.next # Slide `fast` and `target` together until `fast` hits None (index n); # `target` lands on index n - k (k-th from end) and `prev_target` trails by 1. prev_target: Optional[ListNode] = None target: ListNode = head while fast is not None: prev_target = target assert target.next is not None target = target.next fast = fast.next # Case 1 (k == n): `target` is already `head`, so no pointers need to change. if prev_target is None: return head # Save `target.next` before overwriting any `.next` pointers. after_target = target.next # Case 2 (k == n - 1): `head` and `target` are adjacent (head -> target -> after_target). # Must be handled separately: in the general formula, `after_head` would equal `target`, # so `target.next = after_head` would point `target` to itself and create a cycle! if prev_target is head: target.next = head head.next = after_target return target # Case 3 (general, >= 1 node between them): # head -> after_head ... prev_target -> target -> after_target # becomes target -> after_head ... prev_target -> head -> after_target. after_head = head.next target.next = after_head prev_target.next = head head.next = after_target return target def swap_kth_from_end_with_head(values: List[int], k: int) -> List[int]: head = build_list(values) if head is None: return [] new_head = swap_head_with_kth_from_end(head, k) return to_values(new_head)✅ Submit now — all tests should pass.
Intuition & how it works
Picture a freight train of n railcars coupled front-to-back — a singly linked list (a chain of nodes where each node holds a payload and one forward next pointer to the following node) — where you must trade the lead engine (head) with the k-th car from the rear caboose without parking all cars on a side track. To find that car in a single pass using in-place (O(1) auxiliary space) (allocating only a fixed handful of pointer variables regardless of n), we apply the two-pointer fixed-gap technique: advance a scout pointer fast k steps ahead of target, then step both pointers forward together until fast walks off the tail onto None. Because their spacing stays k, target stops directly on the k-th node from the end while a trailing pointer prev_target stops on its predecessor.
Why do simpler shortcuts fail? Dumping nodes into a Python list lets you index nodes[n - k], but that array costs O(n) extra memory. Exchanging head.val and target.val violates the pointer-rewiring rule and breaks callers that keep direct references to ListNode instances expecting their payloads to remain intact. Even when rewiring pointers, applying one generic three-pointer assignment fails whenever head and target sit immediately next to each other (k == n - 1), forming a cycle (self-loop) (an infinite loop where a node's next reference points back to itself).
Let's trace 4 -> 8 -> 12 -> 16 (n = 4) on both a separated exchange (k = 2) and Example 3's adjacent exchange (k = 3):
Chain: 4 -> 8 -> 12 -> 16 -> None
Case A (k = 2, separated):
fast starts at 12; slides 2 steps to None -> prev_target = 8, target = 12, after_target = 16
Rewire: 12.next = 8 (old head.next), 8.next = 4, 4.next = 16
Result: 12 -> 8 -> 4 -> 16 -> None
Case B (k = 3, adjacent — prev_target IS head, Example 3):
fast starts at 16; slides 1 step to None -> prev_target = 4, target = 8, after_target = 12
Rewire: 8.next = 4, 4.next = 12
Result: 8 -> 4 -> 12 -> 16 -> None
Complexity
Let n be the number of nodes in the linked list.
- Time:
O(n).fasttakesksteps in the setup loop andn - ksteps in the lockstep loop (nsteps overall),targettakesn - ksteps, and redirecting the.nextreferences doesO(1)constant work. Building the list for the test harness and reading out the result each add one linearO(n)pass. - Space:
O(1)auxiliary memory for the pointer exchange (plusO(n)for the harness's input/output list serialization).swap_head_with_kth_from_endallocates only five local references (fast,prev_target,target,after_target,after_head) and zero recursion frames.
Edge cases
- Single-node list (
n = 1,k = 1):fastadvances straight toNone, the lockstep loop runs zero iterations,prev_targetremainsNone, andheadis returned untouched. - Target is already at the front (
k == n):prev_targetlikewise staysNone, returning the original chain without modifying any pointers. - Target immediately follows head (
k == n - 1):prev_target is headenters the dedicated two-node swap (target -> head -> after_target), preventing a self-cycle. - Target is the tail (
k = 1,n >= 2):after_targetisNone, sohead.next = after_targetcleanly terminates the relocated tail node. - Three-node tail swap (
n = 3,k = 1):after_headandprev_targetboth reference the middle node; capturingafter_head = head.nextprior to settingprev_target.next = headrewires10 -> 20 -> 30into30 -> 20 -> 10cleanly. - Repeated, zero, or negative payloads: Node positions are tracked by step counts and object identity (
is), never by comparing.val.
Common mistakes
- Mutating
.valinstead of redirecting.next: Satisfies naive value comparisons while breaking the in-place node-relocation requirement. - Omitting the adjacent-node guard (
prev_target is head): Whenhead.next is target, runningtarget.next = head.nextassignstarget.next = target, trapping traversal in an infinite loop. - Clobbering
.nextbefore saving neighbors: Overwritinghead.nextortarget.nextprior to recordingafter_headandafter_targetorphans the remainder of the chain. - Off-by-one gap initialization (
k - 1instead ofk): Startingfastonlyk - 1steps ahead while loopingwhile fast is not Nonemakestargetovershoot by one node (and fails whenk = 1). - Returning
headrather thantarget: Wheneverk < n,headmoves deeper into the list andtargetbecomes the new front node.
Alternative approaches
- Two-pass length measurement: Traverse once to measure
n, returnheadimmediately ifk == n, and otherwise stepn - k - 1links fromheadto reachprev_target. Both approaches performn + (n - k)pointer hops inO(1)extra space; countingnexplicitly can feel simpler if index arithmetic is preferred over two pointers. - Temporary dummy sentinel: Prepending a sentinel (dummy) node (a temporary starter node
dummywithdummy.next = head) givesheadan explicit predecessor (dummy), unifying general two-node swaps so long as identical and adjacent nodes are still guarded.
Follow-up questions
- How would your pointer logic change if you needed to exchange the k-th node from the front with the k-th node from the back? Measure the length
nso the 0-based positions arei = k - 1andj = n - k. Returnheadimmediately ifi == j(same middle node), or swapiandjwheni > jsoi < j. Prepend adummynode ahead ofheadso both targets have predecessorsprev_aandprev_b, handle the adjacent case (a.next is b) separately from the separated case, and returndummy.nextinO(n)time andO(1)auxiliary space. - How should the function behave if k might fall outside the valid range 1 <= k <= n, and how can you detect that in a single pass? Guard
k <= 0up front before entering any loop. Fork > n, checkif fast is None:inside the initialfor _ in range(k)loop before advancingfast = fast.next— hittingNoneearly proves in that same pass that fewer thanknodes exist, allowing you to either raiseValueErroror returnheaduntouched depending on the agreed API contract. - What changes if the input is a doubly linked list with an optional tail pointer? Each node now stores both
.prevand.next, so oncetargetis located its predecessor is immediately available viatarget.prev, and the rewire step must also update.prevontarget(toNone),head,after_head, andafter_target(when non-None). If atailpointer is also maintained, locating thek-th node from the back drops fromO(n)toO(k)by stepping backwardk - 1times via.prevfromtail(and updatingtail = headwheneverk == 1).
Follow-up questions
- How would your pointer logic change if you needed to exchange the k-th node from the front with the k-th node from the back?
- How should the function behave if k might fall outside the valid range 1 <= k <= n, and how can you detect that in a single pass?
- What changes if the input is a doubly linked list with an optional tail pointer?
Similar questions
- Grid Snake Simulation and Hierarchy Validation
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One