Swap Nodes in Pairs

MediumLinked Listin-place reversal

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the head of a singly linked list, swap every two adjacent nodes and return the new head. The first and second nodes trade places, then the third and fourth, and so on. If the list has an odd length, the final node has no partner and stays where it is. Rewire the next pointers rather than exchanging the values stored in the nodes.

Examples

Input: head = [1,2,3,4]
Output: [2,1,4,3]
Pairs (1,2) and (3,4) are each swapped.
Input: head = []
Output: []
Nothing to swap.
Input: head = [1,2,3]
Output: [2,1,3]
Node 3 has no partner and stays last.

Constraints

  • 0 <= number of nodes <= 10^4
  • 0 <= Node.val <= 100

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More in-place reversal problems