Merge Two Sorted Lists
Updated
Problem statement
You are given the heads of two singly linked lists, list1 and list2. Each list is sorted in non-decreasing order.
Merge them into one linked list that is also sorted in non-decreasing order and holds every node of both lists, so repeated values all stay. You may reuse the nodes of the input lists. Return the head of the merged list.
Either list can be empty.
Function
mergeTwoLists(list1: ListNode, list2: ListNode) → ListNodeExamples
Example 1
list1 = [1,3,8]list2 = [2,3,9,10]return = [1,2,3,3,8,9,10]From list1From list2
Take the smaller front value each time: 1, 2, then both 3s, then 8. list1 is used up, so the rest of list2, 9 and 10, goes on the end.
Example 2
list1 = []list2 = [0,4]return = [0,4]list1 is empty, so the answer is list2 as it is.
Example 3
list1 = []list2 = []return = []Both lists are empty, so the merged list is empty too.
Example 4
list1 = [-5,-5,7]list2 = [-6]return = [-6,-5,-5,7]From list1From list2
Negative values and repeats are fine. -6 is the smallest value, and both -5 nodes are kept.
Constraints
- The number of nodes in each list is in the range
[0, 50]. -100 <= Node.val <= 100- Both
list1andlist2are sorted in non-decreasing order.
More WhatNot Onsite Interview questions
- User Journey PathsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Search a 2D MatrixPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Detect Blocked Chat PhrasesPHONE SCREEN · ONSITE INTERVIEW · Seen Jun 2026
- Minimum Remove to Make Valid ParenthesesONSITE INTERVIEW · Seen Dec 2024
- Number of IslandsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2024
- Number of Submatrices That Sum to TargetONSITE INTERVIEW · Seen Jul 2024
- Parse and Store Log RecordsONSITE INTERVIEW · Seen Oct 2023
- Room Occupancy at Query TimesONSITE INTERVIEW · Seen Oct 2023
- K Smallest Values in a StreamPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2022
- Average Purchase PriceONSITE INTERVIEW · Seen Sep 2022
Similar questions at other companies
- Reverse a Singly Linked ListMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Reverse a Singly Linked ListBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Remove Linked List Nodes with a Given ValueExpedia · ONSITE INTERVIEWExpedia interview questions
- Reverse a Linked ListBank of America · ONSITE INTERVIEWBank of America interview questions
- Sorted Doubly Linked List to Balanced BST In PlaceSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Reverse Nodes in K-GroupAmazon · ONSITE INTERVIEW
- Merge K Sorted Linked ListsThe Walt Disney Company · OA · ONSITE INTERVIEWThe Walt Disney Company interview questions
- Merge K Sorted ListsSkydio · ONSITE INTERVIEWSkydio interview questions
- Merge K Sorted Linked Lists Into OneCapital One · ONSITE INTERVIEWCapital One interview questions
- Merge Two Sorted ListsLinkedIn · PHONE SCREENLinkedIn interview questions