Skip to main content

3. Merge Two Sorted Lists

easyAsked at Electronic Arts

Merge two sorted linked lists into one sorted list using pointer manipulation.

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

Problem

You are given the heads of two sorted linked lists. Splice them together into one sorted list and return the head of the merged list.

Constraints

  • 0 <= nodes in each list <= 50
  • -100 <= Node.val <= 100
  • Both lists are sorted in non-decreasing order

Examples

Example 1

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

Example 2

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

Approaches

1. Copy into array then sort

Materialize both lists into an array, sort, rebuild.

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 list from a

Tradeoff:

2. Iterative dummy head

Walk both pointers in tandem, splicing the smaller node into a dummy-headed result list.

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:

Electronic Arts-specific tips

EA values clean iterative pointer code on linked-list questions because gameplay engines like Frostbite touch intrusive linked lists for entity systems.

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

Practice these live with InterviewChamp.AI →