Swap Nodes in Pairs - Problem

Given the head of 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).

For example, if the linked list is 1→2→3→4, the result should be 2→1→4→3.

Input & Output

Example 1 — Four Node List
$ Input: [1,2,3,4]
Output: [2,1,4,3]
💡 Note: Swap pairs (1,2) and (3,4): 1→2→3→4 becomes 2→1→4→3
Example 2 — Odd Length List
$ Input: [1,2,3]
Output: [2,1,3]
💡 Note: Swap pair (1,2), leave 3 unchanged: 1→2→3 becomes 2→1→3
Example 3 — Empty List
$ Input: []
Output: []
💡 Note: Empty list remains empty

Constraints

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

Visualization

Tap to expand
Swap Nodes in Pairs INPUT Original Linked List: 1 2 3 4 Pair 1 Pair 2 Input Array: [1, 2, 3, 4] head --> 1 --> 2 --> 3 --> 4 --> null Swap adjacent pairs without modifying values Constraint: Only change node pointers! ALGORITHM STEPS 1 Initialize Pointers prev, curr = dummy, head 2 Check Pair Exists while curr and curr.next 3 Swap Nodes Rewire prev, curr, next 4 Move Forward prev=curr, curr=curr.next Swap Operation: 1 2 --> 2 1 // Pointer manipulation next_pair = curr.next.next second = curr.next second.next = curr prev.next = second FINAL RESULT Swapped Linked List: 2 1 4 3 Was Pair 1 Was Pair 2 Output Array: [2, 1, 4, 3] OK - Swapped! Complexity: Time: O(n) - single pass Space: O(1) - constant Key Insight: Use a dummy node before head to simplify edge cases. For each pair, save the next pair's start, then rewire: second.next points to first, prev.next points to second, first.next points to next pair. This in-place pointer manipulation achieves O(1) space with O(n) time complexity. TutorialsPoint - Swap Nodes in Pairs | Optimal Solution
Asked in
Facebook 42 Microsoft 38 Amazon 35 Google 28
425.0K Views
High Frequency
~15 min Avg. Time
9.0K 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