Skip to main content

3. Merge Two Sorted Lists

easyAsked at Autodesk

Splice 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 the two lists by splicing the nodes together into a single sorted list and return its head.

Constraints

  • 0 <= node count <= 50
  • -100 <= node value <= 100
  • Both inputs are sorted non-decreasing

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. Dump and sort

Collect all values, sort, rebuild list.

Time
O(n log n)
Space
O(n)
const vals=[]; let p=l1; while(p){vals.push(p.val);p=p.next;}
let q=l2; while(q){vals.push(q.val);q=q.next;}
vals.sort((a,b)=>a-b);

Tradeoff:

2. Two-pointer splice

Walk both lists with a dummy head; attach the smaller node and advance. Single pass, linear time.

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:

Autodesk-specific tips

Linked list merging shows up at Autodesk in BVH leaf merging and undo history splicing, so they value clean pointer manipulation.

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 Autodesk interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →