Back to Practice Dashboard
Top 150 InterviewEasy

Merge Two Sorted Lists

Learn how to solve the 'Merge Two Sorted Lists' problem. This detailed resource details brute force and optimized approaches.

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?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

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

Open in Editor