Skip to main content

3. Merge Two Sorted Lists

easyAsked at Adyen

Merge two sorted linked lists into a single sorted list in O(n+m).

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

Problem

Merge two sorted linked lists into one sorted list by splicing nodes. Return the head of the merged list.

Constraints

  • 0 <= list length <= 50
  • Both lists are sorted ascending.

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

Copy values into an array and sort.

Time
O((n+m) log (n+m))
Space
O(n+m)
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. Iterative splice with dummy head

Use a dummy head and append the smaller current node from each list.

Time
O(n+m)
Space
O(1)
function merge(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:

Adyen-specific tips

Adyen interviewers like dummy-head patterns because the same iterative merge style appears in their settlement-batch pipeline that merges ordered transaction streams from acquiring banks.

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

Practice these live with InterviewChamp.AI →