Merge Two Sorted Lists
Merge two sorted linked lists into one sorted list Example: [1,2,4], [1,3,4] => [1,1,2,3,4,4]
Merge singly linked lists containing integers in non-decreasing order and return the head of the resulting sorted list, preserving every value and duplicate by joining the input nodes. Part 1 merges two lists, and Part 2 accepts an array of lists to merge. Part 3 merges two lists but returns only the first k values of the full merged order, or all values if fewer than k exist. Input lists may be empty, and an empty collection of lists produces an empty result. In Part 3, k = 0 also produces an empty result.
Examples
You write
merge_two_lists(list1: Optional[ListNode], list2: Optional[ListNode])
Example 1
- Input
- list1 = [1,2,4], list2 = [1,3,4]
- returns
- [1,1,2,3,4,4]
Example 2
- Input
- list1 = [], list2 = []
- returns
- []
The pattern behind it
Linked Lists
I reach for it when
- Nodes point to the next node, and you cannot index into the list.
- You must reverse, merge, reorder or remove a node.
Say this before you type. Say which pointers you hold and which link you are about to change.
All 12 Linked Lists problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Each locked part opens in the editor once the part before it passes.
Prep guides that list this problem
Our company tags come from public interview write-ups. None of these is a confirmed question.