Blind 75
20 / 75Free practice

Merge Two Sorted Lists

Easy · Linked lists

Jump to code

Combine two ascending singly linked lists into one ascending list by relinking their nodes. Either input may be empty.

Examples

Example 1

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

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

Example 2

list1 = []
list2 = []

Output: []

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.

Function contract

Linked lists are displayed as value arrays. Your code receives ListNode objects with val and next fields.

Need a hint?

A dummy head removes the special case for the first output node.

Asked in real interviews

Candidates reported versions of Merge Two Sorted Lists from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 8 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    1,
    2,
    4
  ],
  [
    1,
    3,
    4
  ]
]
Expected
[
  1,
  1,
  2,
  3,
  4,
  4
]
Case 2
Input
[
  [],
  []
]
Expected
[]
Case 3
Input
[
  [],
  [
    0
  ]
]
Expected
[
  0
]
Case 4
Input
[
  [
    2,
    4,
    6
  ],
  [
    1,
    3,
    5
  ]
]
Expected
[
  1,
  2,
  3,
  4,
  5,
  6
]
Case 5
Input
[
  [
    1,
    1,
    2
  ],
  [
    1,
    3
  ]
]
Expected
[
  1,
  1,
  1,
  2,
  3
]

Drafts are saved per language in this browser when storage is available.