← Back to Codes

2026-06-09 16:36:42

Merge Two Sorted Lists in Python and Java | LeetCode #21

Learn how to solve Merge Two Sorted Lists in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Merge Two Sorted Lists in Python and Java

In this tutorial, we will learn LeetCode #21: Merge Two Sorted Lists in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Merge Two Sorted Lists Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use two pointers because it gives a clean and optimized solution.

Example input:
list1 = [1, 4, 8], list2 = [2, 3, 9]

Expected result:
Output: [1, 2, 3, 4, 8, 9]

Explanation:
Merge in sorted order.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
list1 = [1, 4, 8], list2 = [2, 3, 9]

Approach:
two pointers

We update variables step by step until we reach:
Output: [1, 2, 3, 4, 8, 9]

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why two pointers is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

list1 = [1, 4, 8], list2 = [2, 3, 9]

We will solve it using two pointers.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: [1, 2, 3, 4, 8, 9]

Why?
Merge in sorted order.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: [1, 2, 3, 4, 8, 9]

Example 1

Input:
list1 = [1, 4, 8], list2 = [2, 3, 9]

Output:
Output: [1, 2, 3, 4, 8, 9]

Explanation:
Merge in sorted order.

Example 2

Input:
list1 = [2, 6, 10], list2 = [1, 5, 7]

Output:
[1, 2, 5, 6, 7, 10]

Explanation:
The two sorted lists are merged in increasing order.

Python Code

Here is the complete Python solution for LeetCode #21.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class SortedListMerger:
    def merge_two_lists(self, list1, list2):
        dummy = ListNode()
        tail = dummy

        while list1 and list2:
            if list1.val <= list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next
            tail = tail.next

        tail.next = list1 if list1 else list2
        return dummy.next


def build_linked_list(values):
    dummy = ListNode()
    current = dummy
    for value in values:
        current.next = ListNode(value)
        current = current.next
    return dummy.next


def linked_list_to_list(head):
    values = []
    while head:
        values.append(head.val)
        head = head.next
    return values


merger = SortedListMerger()
first = build_linked_list([1, 4, 8])
second = build_linked_list([2, 3, 9])
print(linked_list_to_list(merger.merge_two_lists(first, second)))  # Output: [1, 2, 3, 4, 8, 9]

Java Code

Here is the complete Java solution for LeetCode #21.

import java.util.ArrayList;
import java.util.List;

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

class SortedListMerger {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;

        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                tail.next = list1;
                list1 = list1.next;
            } else {
                tail.next = list2;
                list2 = list2.next;
            }
            tail = tail.next;
        }

        tail.next = list1 != null ? list1 : list2;
        return dummy.next;
    }

    private static ListNode buildList(int[] values) {
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;
        for (int value : values) {
            current.next = new ListNode(value);
            current = current.next;
        }
        return dummy.next;
    }

    private static List<Integer> toList(ListNode head) {
        List<Integer> values = new ArrayList<>();
        while (head != null) {
            values.add(head.val);
            head = head.next;
        }
        return values;
    }

    public static void main(String[] args) {
        SortedListMerger merger = new SortedListMerger();
        ListNode first = buildList(new int[] {1, 4, 8});
        ListNode second = buildList(new int[] {2, 3, 9});
        System.out.println(toList(merger.mergeTwoLists(first, second))); // [1, 2, 3, 4, 8, 9]
    }
}

Time and Space Complexity

Time Complexity: O(n log n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #21: Merge Two Sorted Lists becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.