Skip to main content

3. Merge Two Sorted Lists

easyAsked at Freshworks

Merge 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 linked lists list1 and list2. Merge them in sorted order and return the head of the merged list.

Constraints

  • 0 <= list length <= 50
  • -100 <= Node.val <= 100

Examples

Example 1

Input
list1=[1,2,4], list2=[1,3,4]
Output
[1,1,2,3,4,4]

Example 2

Input
list1=[], list2=[0]
Output
[0]

Approaches

1. Collect and sort

Flatten both lists into an array, sort, rebuild.

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);

Tradeoff:

2. Two-pointer merge

Walk both lists, pick the smaller head each step. Classic merge step.

Time
O(n+m)
Space
O(1)
function merge(l1, l2) {
  const d = { next: null }; let t = d;
  while (l1 && l2) {
    if (l1.val <= l2.val) { t.next = l1; l1 = l1.next; }
    else { t.next = l2; l2 = l2.next; }
    t = t.next;
  }
  t.next = l1 || l2;
  return d.next;
}

Tradeoff:

Freshworks-specific tips

Freshworks values clean pointer manipulation — narrate the dummy-node trick so the interviewer sees the pattern.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Merge Two Sorted Lists and other Freshworks interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →