3. Merge Two Sorted Lists
easyAsked at GitHubMerge two sorted linked lists into one sorted list — GitHub treats this as the toy version of merging two sorted commit-date streams during git log --merge.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the heads of two sorted linked lists list1 and list2, merge them into a single sorted list by splicing nodes together. Return the head of the merged list.
Constraints
0 <= total nodes <= 50-100 <= Node.val <= 100
Examples
Example 1
list1 = [1,2,4], list2 = [1,3,4][1,1,2,3,4,4]Example 2
list1 = [], list2 = [0][0]Approaches
1. Brute force
Collect all values into array, sort, rebuild list.
- Time
- O((n+m) log(n+m))
- Space
- O(n+m)
const vals = [];
while(l1){vals.push(l1.val);l1=l1.next;}
while(l2){vals.push(l2.val);l2=l2.next;}
vals.sort((a,b)=>a-b);Tradeoff:
2. Two-pointer splice
Walk both lists with a dummy head; attach whichever node has the smaller value, then advance that pointer. Linear in total length.
- 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:
GitHub-specific tips
GitHub interviewers ask 'now extend this to k lists with min-heap' — the natural lead-in to git log --merge across multiple branch tips.
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 GitHub interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →