Skip to main content

24. Swap Nodes in Pairs

medium

Swap every two adjacent nodes in a singly linked list — without altering node values. A miniature version of Reverse Nodes in k-Group with k=2, perfect for drilling the dummy-head plus three-pointer rewire pattern.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed).

Constraints

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

Examples

Example 1

Input
head = [1,2,3,4]
Output
[2,1,4,3]

Example 2

Input
head = []
Output
[]

Example 3

Input
head = [1]
Output
[1]

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

A dummy head simplifies the very first swap, which would otherwise need to change the head pointer.

Hint 2

For each pair, you need three pointers: the node before the pair, the first node of the pair, the second node of the pair. Rewire them all in one fixed sequence.

Hint 3

After swapping a pair, advance your 'previous' pointer to the new tail of that pair so the next iteration handles the next two nodes cleanly.

Solution approach

Reveal approach

Dummy-head with three-pointer rewiring. Allocate a dummy node and link dummy.next = head. Use prev = dummy. Loop while prev.next and prev.next.next are both non-null: let first = prev.next and second = prev.next.next. Rewire in fixed order: first.next = second.next; second.next = first; prev.next = second. Now the pair is swapped and first is the tail of this swapped pair. Advance prev = first and continue. Return dummy.next. Recursive variant: pair up head and head.next, recurse on head.next.next, then rewire. O(n) time, O(1) extra space iteratively (O(n) recursion stack for the recursive version).

Complexity

Time
O(n)
Space
O(1)

Related patterns

  • linked-list
  • dummy-head
  • pointer-rewiring
  • in-place-linked-list-reversal

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Microsoft
  • Meta
  • Bloomberg

Practice these live with InterviewChamp.AI

Drill Swap Nodes in Pairs and Linked Lists problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →