Skip to main content

3. Merge Two Sorted Lists

easyAsked at Swiggy

Merge 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. Splice them together into a single sorted list by reusing the existing nodes and return the new head.

Constraints

  • 0 <= list length <= 50
  • -100 <= node.val <= 100
  • 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=[]
Output
[]

Approaches

1. Collect-and-sort

Dump both into an array, sort, rebuild list.

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

Tradeoff:

2. Two-pointer splice

Walk both heads, splice smaller node onto a dummy tail. Keeps O(1) extra space.

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

Swiggy-specific tips

Swiggy interviewers want the iterative splice — frame it like merging two sorted courier ETA streams into one.

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

Practice these live with InterviewChamp.AI →