Skip to main content

3. Merge Two Sorted Lists

easyAsked at Riot Games

Merge two sorted linked lists into one — Riot uses this to test pointer hygiene before queue-merge matchmaking questions.

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

Problem

Given the heads of two sorted singly linked lists, merge them into a single sorted list and return its head. Do not allocate new nodes; splice the existing ones.

Constraints

  • 0 <= total nodes <= 50
  • -100 <= Node.val <= 100
  • Both lists sorted non-decreasing

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

Dump both lists into an array, sort, rebuild.

Time
O((n+m) log(n+m))
Space
O(n+m)
const arr = [];
for (let p=l1;p;p=p.next) arr.push(p.val);
for (let p=l2;p;p=p.next) arr.push(p.val);
arr.sort((a,b)=>a-b);
// rebuild list

Tradeoff:

2. Two-pointer splice

Advance whichever head is smaller and append to a dummy tail.

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:

Riot Games-specific tips

Riot reviewers value the in-place splice because it mirrors how matchmaking queues merge rank-sorted player buckets without copying state across the server tick boundary.

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

Practice these live with InterviewChamp.AI →