Facebook PixelMerge Two Sorted Lists — Coding Practice
Merge Two Sorted ListsEasy

Merge Two Sorted Lists

Easy 21.3k65% acceptance
Linked ListRecursion

You are given the heads of two linked lists, list1 and list2, each already sorted in non-decreasing order.

Splice the two lists together into a single sorted list by reusing the existing nodes, and return the head of the merged list.

Each list is given to you as a ListNode ({ val, next }); an empty list is null. Return the head of the combined sorted list.

Example 1
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Interleaving the two sorted lists keeps the result sorted: 1,1,2,3,4,4.
Example 2
Input: list1 = [], list2 = []
Output: []
Example 3
Input: list1 = [], list2 = [0]
Output: [0]
Constraints
  • The number of nodes in each list is in the range [0, 50].
  • -100 ≤ Node.val ≤ 100
  • Both `list1` and `list2` are sorted in non-decreasing order.
Asked atAmazonMicrosoftAppleMeta
JavaScript
Loading editor…
Case 1
[1,2,4], [1,3,4]
expected: [1,1,2,3,4,4]
Case 2
[], []
expected: []
Case 3
[], [0]
expected: [0]
Case 4
[5], [1,2,4]
expected: [1,2,4,5]
Case 5
[-3,1], [-2,0,4]
expected: [-3,-2,0,1,4]
Case 6
[1,2,3], []
expected: [1,2,3]