Introduction
The Merge Two Sorted Linked Lists problem is a very common DSA interview question, especially in linked list topics. It tests your understanding of pointers, node manipulation, and handling edge cases.
In simple words, this problem asks you to combine two already sorted linked lists into one single sorted linked list.
This article explains the problem in simple, human-friendly language, step by step, with examples and interview-ready code.
What is a Linked List?
A Linked List is a linear data structure in which elements (nodes) are connected via pointers.
Each node contains:
A data value
A pointer to the next node
Unlike arrays, linked lists do not store elements in continuous memory locations.
What Does “Sorted Linked List” Mean?
A sorted linked list means the values inside the list are already arranged in increasing order.
Example
List 1: 1 → 3 → 5
List 2: 2 → 4 → 6
Both lists are individually sorted.
Problem Statement
You are given the heads of two sorted linked lists. Your task is to merge them into a single sorted linked list and return the head of the new list.
Example
Input:
List1 = 1 → 3 → 5
List2 = 2 → 4 → 6
Output:
1 → 2 → 3 → 4 → 5 → 6
Why Brute Force is Not Ideal
A naive approach could be:
Copy all values into an array
Sort the array
Create a new linked list
Problems with This Approach
Extra space required
Sorting adds unnecessary time
Interviewers expect a pointer-based solution.
Optimized Approach Using Two Pointers
The best approach is to use two pointers, one for each linked list.
Key Idea
Compare the current nodes of both lists
Pick the smaller value
Move the pointer forward
This keeps the list sorted without extra space.
Step-by-Step Explanation
Steps:
Create a dummy node (to simplify logic)
Use a
currentpointer starting from dummyCompare values of both list nodes
Attach the smaller node to
currentMove the pointer of the chosen list
Continue until one list ends
Attach the remaining part of the other list
Dry Run Example
List1: 1 → 3 → 5
List2: 2 → 4 → 6
Join the conversation! Your thoughts help the community grow.