Skip to main content

3. Merge Two Sorted Lists

easyAsked at Wix

Merge two sorted linked lists; Wix uses this pattern when merging revision histories of two collaborators editing the same template.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

You are given the heads of two sorted linked lists. Merge them into a single sorted list by splicing nodes; return the new head.

Constraints

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

Examples

Example 1

Input
l1=[1,2,4], l2=[1,3,4]
Output
[1,1,2,3,4,4]

Example 2

Input
l1=[], l2=[0]
Output
[0]

Approaches

1. Brute force

Collect all values into an array, sort, rebuild list.

Time
O((n+m) log(n+m))
Space
O(n+m)
const a=[]; while(l1){a.push(l1.val);l1=l1.next} while(l2){a.push(l2.val);l2=l2.next} a.sort((x,y)=>x-y); // rebuild

Tradeoff:

2. Two pointers

Walk both lists, splicing the smaller node into the dummy result.

Time
O(n+m)
Space
O(1)
function mergeTwoLists(l1,l2){
  const dummy={next:null}; let t=dummy;
  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 dummy.next;
}

Tradeoff:

Wix-specific tips

Wix interviewers like a quick aside on how merging is in-place vs allocating — they care because their template-render path runs in tight memory budgets on the edge.

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

Practice these live with InterviewChamp.AI →