3. Merge Two Sorted Lists
easyAsked at CanvaMerge two sorted linked lists into one — Canva uses this to test pointer hygiene and stable ordering, mirroring how template content streams are merged.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list by splicing nodes and return the head.
Constraints
0 <= n1, n2 <= 50-100 <= node values <= 100Lists are non-decreasing
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-and-sort
Push all values, sort, rebuild list.
- Time
- O(n log n)
- Space
- O(n)
const arr = [];
let p = l1; while (p) { arr.push(p.val); p = p.next; }
p = l2; while (p) { arr.push(p.val); p = p.next; }
arr.sort((a,b)=>a-b);Tradeoff:
2. Two-pointer splice
Walk both lists, attach the smaller node to a dummy head, advance. O(n+m) and in-place.
- Time
- O(n+m)
- Space
- O(1)
function merge(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:
Canva-specific tips
Canva values clean dummy-node idioms and explicit null handling, since editor data structures often have sentinel-bordered linked element trees.
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 Canva interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →