3. Merge Two Sorted Lists
easyAsked at DuolingoMerge two sorted linked lists into one sorted list.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given the heads of two sorted singly linked lists. Splice them together into a single sorted linked list and return the new head. The new list should be made by reusing the nodes of the two input lists.
Constraints
0 <= each list length <= 50-100 <= Node.val <= 100Both lists are sorted ascending
Examples
Example 1
l1 = [1,2,4], l2 = [1,3,4][1,1,2,3,4,4]Example 2
l1 = [], l2 = [0][0]Approaches
1. Collect and sort
Push every value into an array, sort, and rebuild a list.
- Time
- O((n+m) log(n+m))
- Space
- O(n+m)
const vals = [];
for (let p of [l1,l2]) while (p) { vals.push(p.val); p = p.next; }
vals.sort((a,b)=>a-b);Tradeoff:
2. Two-pointer splice
Walk both lists with two pointers, attach the smaller head, advance, and append the leftover tail.
- Time
- O(n+m)
- Space
- O(1)
function mergeTwoLists(l1, l2) {
const dummy = { next: null };
let tail = dummy;
while (l1 && l2) {
if (l1.val <= l2.val) { tail.next = l1; l1 = l1.next; }
else { tail.next = l2; l2 = l2.next; }
tail = tail.next;
}
tail.next = l1 || l2;
return dummy.next;
}Tradeoff:
Duolingo-specific tips
Duolingo learners progress through ordered skill queues; talk about how this is the core merge step inside a spaced-repetition review scheduler.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Merge Two Sorted Lists and other Duolingo interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →