Top 150 InterviewEasy

Merge Two Sorted Lists

Detailed guide and Python implementation for the 'Merge Two Sorted Lists' problem.

Problem Statement

Easy

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.

The linked lists are represented as Python lists. Implement a function mergeTwoLists(list1: list, list2: list) -> list that returns the merged sorted list.

Constraints
  • The number of nodes in both lists is in the range [0, 50]
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order

Examples

Example 1
Input
[1,2,4], [1,3,4]
Output
[1,1,2,3,4,4]
Explanation

Merging 1->2->4 and 1->3->4 gives 1->1->2->3->4->4.

Example 2
Input
[], []
Output
[]
Explanation

Both lists are empty, so the merged list is also empty.

Example 3
Input
[], [0]
Output
[0]
Explanation

Merging an empty list with [0] gives [0].

Need a Hint?
Consider using Linked List-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.