3. Merge Two Sorted Lists
easyAsked at RampMerge two sorted linked lists into one sorted list by splicing nodes together.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the heads of two sorted singly linked lists, splice them into a single sorted list and return its head. Reuse the existing nodes; do not allocate new ones.
Constraints
0 <= nodes in each list <= 50-100 <= Node.val <= 100Both lists are sorted non-decreasing
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 all values into array, sort, rebuild list.
- Time
- O(n log n)
- Space
- O(n)
const arr=[];while(l1){arr.push(l1.val);l1=l1.next}while(l2){arr.push(l2.val);l2=l2.next}arr.sort((a,b)=>a-b);// rebuildTradeoff:
2. Two-pointer splice
Walk both pointers, attach smaller node to tail, advance. Linear time, no extra allocation.
- 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:
Ramp-specific tips
Ramp often reframes this as merging two sorted streams of card transactions while preserving stable ordering for ledger postings, so emphasize O(1) extra space and stable tie-breaks.
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 Ramp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →