~/coding-interview/leetcode-swap-nodes-pairs-link-list.md

Swap Nodes Pairs in Link List - Leet Code Solution

// TL;DR

Iterative pointer manipulation — swap each pair by redirecting next pointers, use a prev pointer to stitch pairs together. O(n) time, O(1) space.

Swap Nodes Pairs in Link List - Leet Code Solution

Problem Statement

Given a linked list, swap every two adjacent nodes and return its head. You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Solution

  • Lets look at the first two nodes first.
  • We need to move head to second. (One time operation)
  • Move next of First to next of Second
  • Move next of Second to First
  • All looks fine. We can go like this in pairs.
  • Now, what about joining the pairs?
  • We need another pointer who will be responsible of joining these pairs.

Code

public static class ListNode {
	int val;
	ListNode next;
	ListNode(int x) { val = x; }
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		ListNode t = this;
		while (t != null) {
			sb.append(t.val).append(" -> ");
			t = t.next;
		}
		return sb.toString();
	}
}

public ListNode swapPairs(ListNode head) {
	if (head == null || head.next == null) return head;
	
	ListNode first = head;
	ListNode second = head.next;
	ListNode prev = null;
	
	ListNode result = second;
	while (first != null && second != null) {
		first.next = second.next;
		second.next = first;
		
		if (prev != null) {
			prev.next = second;
		}
		
		prev = first;
		
		first = first.next;
		if (first != null) {
			second = first.next;
		}
	}
	
	return result;
}

Leet Code submission result

Runtime: 0 ms, faster than 100.00% of Java online submissions for Swap Nodes in Pairs. Memory Usage: 34.5 MB, less than 100.00% of Java online submissions for Swap Nodes in Pairs.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…