Sitemap
Akansha Saraswat

Akansha Saraswat

Software Engineer by profession, Passionate for fitness, Over thinker - Penning down my learnings

Member-only story

Swap Nodes in Pairs — Leetcode Pattern Recognition Practice

2 min readJan 11, 2026

--

https://leetcode.com/problems/swap-nodes-in-pairs/

Problem: Swap every two adjacent nodes in a linked list and return its head.

Pattern

Linked List reversal pattern

This problem is essentially Reverse Nodes in k-Group where k = 2 for every group.

Once that clicks, the solution becomes very mechanical.

Intuition (My Way)

  • Since swapping pairs means reversing every adjacent pair, I treated the list in chunks of size 2.
  • Instead of writing a special-case solution, I reused the same iterative k-group reversal logic.
  • A dummy node helps simplify edge cases and keeps pointer updates clean.

For every iteration:

  • Find the 2nd node from the current start.
  • Reverse the nodes between start.next and kth.next.
  • Re-link the reversed part back to the main list.
  • Move start forward to prepare for the next pair.

This avoids recursion and keeps everything pointer-based.

Complexity

  • Time Complexity: O(n) — each node is visited once
  • Space Complexity: O(1) — in-place reversal, no extra data structures
class Solution(object):
def swapPairs(self, head)…

--

--

Akansha Saraswat
Akansha Saraswat

Written by Akansha Saraswat

Software Engineer by profession, Passionate for fitness, Over thinker - Penning down my learnings