Swap Nodes in Pairs - Problem
Swap Adjacent Node Pairs in a Linked List

Imagine you have a chain of connected nodes, and you need to swap every two adjacent nodes while keeping the chain intact. Given the head of a linked list, your task is to swap every two adjacent nodes and return the new head of the modified list.

Key Rules:
  • You can only change the node connections - not the values inside the nodes
  • If there's an odd number of nodes, the last node remains in its original position
  • The solution should work in-place without creating new nodes

Example: 1→2→3→4 becomes 2→1→4→3

Input & Output

example_1.py — Basic Even Length List
$ Input: head = [1,2,3,4]
Output: [2,1,4,3]
💡 Note: The first pair (1,2) swaps to (2,1), and the second pair (3,4) swaps to (4,3). Result: 2→1→4→3
example_2.py — Odd Length List
$ Input: head = [1,2,3]
Output: [2,1,3]
💡 Note: The first pair (1,2) swaps to (2,1), but node 3 has no pair so it remains in place. Result: 2→1→3
example_3.py — Edge Cases
$ Input: head = [] OR head = [1]
Output: [] OR [1]
💡 Note: Empty list returns empty. Single node has no pair to swap with, so it remains unchanged.

Constraints

  • The number of nodes in the list is in the range [0, 100]
  • 0 ≤ Node.val ≤ 100
  • You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed)

Visualization

Tap to expand
Dancing Partners Swap VisualizationDir🕺1💃2🕺3💃4Pair 1 - Ready to Swap!Pair 2 - Next in LineAfter First Swap:Dir💃2🕺1🕺3💃4✓ Swapped!Final Result (All Pairs Swapped):💃2🕺1💃4🕺3
Understanding the Visualization
1
Setup Stage
Place a director (dummy node) at the front to coordinate the swaps
2
Identify Partners
Point to the next two dancers who need to swap positions
3
Coordinate Swap
Carefully rewire connections so partners swap without breaking the line
4
Move to Next Pair
Director moves to supervise the next pair of dancers
Key Takeaway
🎯 Key Insight: Use a dummy node as an anchor and maintain careful pointer tracking to swap pairs efficiently without losing connections in the linked list.
Asked in
Microsoft 45 Amazon 38 Google 32 Meta 28 Apple 22
52.3K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen