Merge Two Sorted Linked Lists
Updated
Problem statement
You are given the heads of two singly linked lists, each sorted from smallest to largest. Merge them into one list sorted from smallest to largest and return its head.
Reuse and relink the original nodes; keep every node exactly once. Both input lists are acyclic and share no nodes. Either list may be empty. When the current values are equal, take the node from list1 first; preserve the order within each input list.
In the input and output, a linked list is shown as an array of its values. An empty array represents a null head. The input lists always follow the sorted and no-shared-nodes rules above.
Function
mergeTwoLists(list1: ListNode, list2: ListNode) → ListNodeExamples
Example 1
list1 = [1,2,4]list2 = [1,3,4]return = [1,1,2,3,4,4]The first list holds one, two, four and the second holds one, three, four. When the front values tie, the node from the first list goes first. Relinking in sorted order gives one, one, two, three, four, four.
Example 2
list1 = []list2 = [0]return = [0]The first list is empty, so the merged list is just the second list, which has a single node with value zero. The answer is that one node.
Example 3
list1 = []list2 = []return = []Both lists are empty, so there are no nodes to link. The merged list is empty.
Constraints
0 <= total number of nodes <= 100000.-10^9 <= node.val <= 10^9.- Each input is sorted in nondecreasing order, acyclic and disjoint from the other input.
More Salesforce Phone Screen questions
- Detect a Cycle in a Linked ListPHONE SCREEN · Seen Oct 2026
- Find Rows Common to Two TablesPHONE SCREEN · Seen Oct 2026
- Minimum Window of Required WordsPHONE SCREEN · Seen Aug 2026
- Permutations of Unique CharactersPHONE SCREEN · Seen Aug 2026
- Minimum Window SubstringPHONE SCREEN · Seen Aug 2026
- Optimal Account BalancingPHONE SCREEN · Seen Jul 2026
- Longest Increasing SubsequencePHONE SCREEN · Seen Jul 2026
- Maximal SquarePHONE SCREEN · Seen Jul 2026
- ATM Queue Exit OrderPHONE SCREEN · Seen May 2026
- Good Ways to Split an ArrayPHONE SCREEN · Seen May 2026
Similar questions at other companies
- Merge Two Sorted ListsLinkedIn · PHONE SCREENLinkedIn interview questions
- Middle of a Linked ListCisco · PHONE SCREENCisco interview questions
- Merge Two Sorted ListsIBM · PHONE SCREENIBM interview questions
- Count Nodes in a ChainApple · PHONE SCREENApple interview questions
- Find the Intersection Node of Two Linked ListsVisa · PHONE SCREENVisa interview questions
- Reverse a Linked ListMygate · PHONE SCREENMygate interview questions
- Linked List Palindrome in Constant SpaceNVIDIA · PHONE SCREENNVIDIA interview questions
- First Node Two Linked Lists ShareAdobe · PHONE SCREENAdobe interview questions
- Reverse a Singly Linked ListBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Merge Two Sorted Linked ListsExpedia · PHONE SCREEN · ONSITE INTERVIEWExpedia interview questions