Swapping Nodes in a Linked List

Medium

Topics
Linked ListTwo Pointers

Given the head of a linked list and an integer k, swap the values of the k-th node from the beginning and the k-th node from the end (1-indexed), then return the head.

Example 1

before12345null
after14325null
The 2th from the front (index 1) and the 2th from the back (index 3) exchange.
Linked list values from head to tail.
Input:  head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]

Example 2

before7966783095null
after7966873095null
Input:  head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]

Constraints

  • 1 <= k <= number of nodes <= 10^5
  • 0 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

The problem asks to swap values, so no relinking is needed — the work is locating the two nodes in a single pass without knowing the length in advance.

The two-pointer gap does it. Walk first forward k - 1 steps so it sits on the k-th node from the start. Now start a second pointer at the head and advance both until first reaches the tail: the gap between them is fixed, so when the leader is at the end, the follower is exactly k nodes from it — the k-th node from the end.

Approach

  1. Advance first by k - 1 to reach the k-th node from the start.
  2. Set second to the head and cur to first.
  3. Advance cur and second together until cur is the last node.
  4. Swap the two values.

Dry Run

input  1 -> 2 -> 3 -> 4 -> 5      k = 2

first walks k-1 = 1 step   ->  node 2

  cur     second
  2       1
  3       2
  4       3
  5       4        cur is the tail, so second is the 2nd node from the end

swap 2 and 4

answer  1 -> 4 -> 3 -> 2 -> 5

  [7,9,6,6,7,8,3,0,9,5] k=5  ->  7 -> 9 -> 6 -> 6 -> 8 -> 7 -> 3 -> 0 -> 9 -> 5
  [1]     k=1  ->  1          both pointers land on the same node, a no-op
  [1,2]   k=1  ->  2 -> 1

Complexity

  • Time — O(n): one pass. The k-1 walk and the gap walk together cover the list once.
  • Space — O(1): three pointers.

Common Pitfalls

  • Making two separate passes, one to measure the length and one to find node n - k + 1. It is correct and still O(n), but the gap technique is the point of the exercise.
  • Off-by-one in the gap. first advances k - 1 times, not k; and the follower stops when the leader is on the last node, not past it.
  • Relinking the nodes instead of swapping values. The problem asks for the values, and relinking two arbitrary nodes correctly is considerably fiddlier — especially when they are adjacent or the same node.
  • Special-casing k in the middle of the list. When both pointers land on the same node the swap is a no-op and needs no branch.
  • Assuming k is within range and omitting the reasoning. The constraints guarantee 1 <= k <= n, which is exactly what makes the unguarded k-1 walk safe.
  • Collecting all values into an array, swapping, and writing back. O(n) space for a problem that needs none.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def swapNodes(self, head, k):
        first = head
        for _ in range(k - 1):
            first = first.next
        second = head
        cur = first
        while cur.next:
            cur = cur.next
            second = second.next
        first.val, second.val = second.val, first.val
        return head
SensAI
Beta
Tap the mic to stop voice mode