LeetCode 21: Merge Two Sorted Lists Solution

Master LeetCode problem 21 (Merge Two Sorted Lists), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

21. Merge Two Sorted Lists

Problem Explanation

Explanation

To merge two sorted linked lists, we can iterate through both lists simultaneously, comparing the values at each node, and linking the nodes in ascending order. We maintain a dummy node as the head of the merged list, and we move a pointer through the merged list while updating the next pointers to connect the nodes in sorted order. Finally, we return the next of the dummy node, which is the head of the merged sorted list.

  • Time complexity: O(m + n) where m and n are the lengths of the two input lists
  • Space complexity: O(1)

Solution Code

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

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode curr = dummy;

    while (l1 != null && l2 != null) {
        if (l1.val < l2.val) {
            curr.next = l1;
            l1 = l1.next;
        } else {
            curr.next = l2;
            l2 = l2.next;
        }
        curr = curr.next;
    }

    if (l1 != null) {
        curr.next = l1;
    } else {
        curr.next = l2;
    }

    return dummy.next;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 21 (Merge Two Sorted Lists)?

This page provides optimized solutions for LeetCode problem 21 (Merge Two Sorted Lists) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 21 (Merge Two Sorted Lists)?

The time complexity for LeetCode 21 (Merge Two Sorted Lists) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 21 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 21 in Java, C++, or Python.

Back to LeetCode Solutions