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 ListNode instances by updating .next references rather than copying or swapping .val attributes.
  • 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 = 1 refers to the last node in the chain, k = 2 refers to the second-to-last node, and k = n refers 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, where n = len(values)
  • 1 <= k <= n
  • -10^9 <= values[i] <= 10^9
  • The linked-list swap itself must run in O(n) time and O(1) extra space.

Step-by-step walkthrough

  1. Restate the problem

    We receive a singly linked list containing n nodes and a 1-based count k (1 <= k <= n), and we need to exchange the first node (head) with the k-th node counted from the back, returning the updated head node:

    • Counting from the tail is 1-indexed: k = 1 selects the last node (0-based position n - 1), k = 2 selects the penultimate node (n - 2), and k = n selects head itself (0).
    • Rewire .next references directly instead of mutating .val payloads 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 a List[int] back, our entry function constructs a linked list, executes the O(1)-space pointer exchange, and collects the resulting sequence of node values.

  2. Why array indexing and value swapping break the rules

    A naive attempt pushes every node into a Python list and swaps .val attributes:

    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 head
    

    That violates both core constraints: nodes consumes O(n) auxiliary memory, and overwriting .val corrupts callers holding external references to specific ListNode objects.

    To physically relocate target to the front and place head into target's former position in a one-way chain, we need references to both target and prev_target (the predecessor node whose .next link must now point to head).

  3. Locate target and prev_target in O(1) memory with a fixed-gap ruler

    Think of placing a rigid spacer of width k at the front of the list: target starts on head (index 0) while fast steps k nodes forward to index k. Next, advance both pointers in lockstep one node at a time until fast walks off the tail onto None (index n). Because their separation stays fixed at k, target stops on index n - k while prev_target trails one node behind at n - 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.next
    
  4. Sketch all three pointer-swap configurations first

    Before modifying any .next attribute, map out the three distinct layouts of target relative to head:

    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 if branch? Whenever head and target are neighbors, after_head (head.next) is target itself! Running Case 3's assignment target.next = after_head would execute target.next = target, creating an infinite self-loop.

  5. Code the in-place pointer swap

    Store after_target = target.next and (for Case 3) after_head = head.next in local variables before mutating any .next reference. Capturing both neighbors up front also handles the 3-node tail exchange (10 -> 20 -> 30, k = 1, where after_head and prev_target both point to 20) 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 target
    
  6. Code the list conversion helpers and judge wrapper

    build_list attaches nodes onto a dummy sentinel so the loop body has no empty-list special case, while to_values walks from new_head until None to 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)
    
  7. 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 -> 16
    
  8. Complete 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). fast takes k steps in the setup loop and n - k steps in the lockstep loop (n steps overall), target takes n - k steps, and redirecting the .next references does O(1) constant work. Building the list for the test harness and reading out the result each add one linear O(n) pass.
  • Space: O(1) auxiliary memory for the pointer exchange (plus O(n) for the harness's input/output list serialization). swap_head_with_kth_from_end allocates 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): fast advances straight to None, the lockstep loop runs zero iterations, prev_target remains None, and head is returned untouched.
  • Target is already at the front (k == n): prev_target likewise stays None, returning the original chain without modifying any pointers.
  • Target immediately follows head (k == n - 1): prev_target is head enters the dedicated two-node swap (target -> head -> after_target), preventing a self-cycle.
  • Target is the tail (k = 1, n >= 2): after_target is None, so head.next = after_target cleanly terminates the relocated tail node.
  • Three-node tail swap (n = 3, k = 1): after_head and prev_target both reference the middle node; capturing after_head = head.next prior to setting prev_target.next = head rewires 10 -> 20 -> 30 into 30 -> 20 -> 10 cleanly.
  • Repeated, zero, or negative payloads: Node positions are tracked by step counts and object identity (is), never by comparing .val.

Common mistakes

  • Mutating .val instead of redirecting .next: Satisfies naive value comparisons while breaking the in-place node-relocation requirement.
  • Omitting the adjacent-node guard (prev_target is head): When head.next is target, running target.next = head.next assigns target.next = target, trapping traversal in an infinite loop.
  • Clobbering .next before saving neighbors: Overwriting head.next or target.next prior to recording after_head and after_target orphans the remainder of the chain.
  • Off-by-one gap initialization (k - 1 instead of k): Starting fast only k - 1 steps ahead while looping while fast is not None makes target overshoot by one node (and fails when k = 1).
  • Returning head rather than target: Whenever k < n, head moves deeper into the list and target becomes the new front node.

Alternative approaches

  • Two-pass length measurement: Traverse once to measure n, return head immediately if k == n, and otherwise step n - k - 1 links from head to reach prev_target. Both approaches perform n + (n - k) pointer hops in O(1) extra space; counting n explicitly can feel simpler if index arithmetic is preferred over two pointers.
  • Temporary dummy sentinel: Prepending a sentinel (dummy) node (a temporary starter node dummy with dummy.next = head) gives head an 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 n so the 0-based positions are i = k - 1 and j = n - k. Return head immediately if i == j (same middle node), or swap i and j when i > j so i < j. Prepend a dummy node ahead of head so both targets have predecessors prev_a and prev_b, handle the adjacent case (a.next is b) separately from the separated case, and return dummy.next in O(n) time and O(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 <= 0 up front before entering any loop. For k > n, check if fast is None: inside the initial for _ in range(k) loop before advancing fast = fast.next — hitting None early proves in that same pass that fewer than k nodes exist, allowing you to either raise ValueError or return head untouched 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 .prev and .next, so once target is located its predecessor is immediately available via target.prev, and the rewire step must also update .prev on target (to None), head, after_head, and after_target (when non-None). If a tail pointer is also maintained, locating the k-th node from the back drops from O(n) to O(k) by stepping backward k - 1 times via .prev from tail (and updating tail = head whenever k == 1).

Follow-up questions

Similar questions

More Amplitude interview questions

All 2 Amplitude questions →