Skip to main content

39. Swap Nodes in Pairs

mediumAsked at Workday

Swap every two adjacent nodes in a linked list. Workday uses this for fine pointer surgery — the same wrangling needed to merge adjacent payroll segments without losing the chain.

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

Source citations

Public interview reports confirming this problem appears in Workday loops.

  • Glassdoor (2025)Workday SDE2 phone screen.

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]

Approaches

1. Swap values only

Walk pairs, swap values.

Time
O(n)
Space
O(1)
// disallowed by the prompt — must swap nodes themselves

Tradeoff: Trivial but prompt-forbidden.

2. Iterative pointer rewire with dummy

Dummy head. prev points before each pair. Rewire prev -> second -> first -> rest.

Time
O(n)
Space
O(1)
function swapPairs(head) {
  const dummy = { val: 0, next: head };
  let prev = dummy;
  while (prev.next && prev.next.next) {
    const first = prev.next;
    const second = first.next;
    first.next = second.next;
    second.next = first;
    prev.next = second;
    prev = first;
  }
  return dummy.next;
}

Tradeoff: Three pointer swaps per pair. The order matters — wiring first.next BEFORE second.next first would lose the rest of the list.

Workday-specific tips

Workday grades on pointer-swap ORDER. There are exactly 3 rewires per pair: first.next = second.next (preserve tail), second.next = first (swap), prev.next = second (attach). Walk this order out loud before coding.

Common mistakes

  • Wrong swap order — losing the tail of the list.
  • Forgetting to advance prev to first (the new tail of the swapped pair).
  • No dummy head — swapping the first pair is special.

Follow-up questions

An interviewer at Workday may pivot to one of these next:

  • Reverse Nodes in k-Group (LC 25) — generalize to k.
  • Rotate List (LC 61).
  • Recursive version.

Solve it now

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

Output

Press Run or Cmd+Enter to execute

FAQ

Why dummy head?

Uniform handling of the first pair. Without it, the first pair needs a special swap that returns a new head.

Recursive vs iterative?

Recursive is shorter but uses O(n) stack. For n=100 it's fine, but iterative is the safer pattern.

Practice these live with InterviewChamp.AI

Drill Swap Nodes in Pairs and other Workday interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →