← Microsoft bank

Microsoft · Question 16 · Linked Lists

Merge Two Sorted Lists

Linked ListsJavacode⏱ O(n + m)💾 O(n + m)
Product-based

Problem

Given two sorted linked lists, merge them into one sorted list and return it.

Approach

Recursively attach the smaller head and merge the rest.

Time O(n + m)Space O(n + m)

How it works

  1. 1Empty list returns the other one.
  2. 2Attach the smaller head, recurse on the rest.

Sample input / output

Input:
3
1 2 4
3
1 3 4
Output:
[1, 1, 2, 3, 4, 4]

Constraints

0 <= nodes <= 50; -100 <= Node.val <= 100; both lists sorted.

Solution — read it, then walk it

Time O(n + m)Space O(n + m)Loops 4Branches 3Returns 3source · Java
Scroll sideways for wide charts — the view follows the active step.
yesnoSTARTimport java.util.*DEFINE class MainDEFINE static ListNodemergeTwoLists(ListNode l1,ListNode l2)if (l1 == null) returnl2if (l2 == null) returnl1if (l1.val < l2.val)l1.next =mergeTwoLists(l1.next, l2)RETURN l1} elseDEFINE class ListNodeDEFINE valListNode nextListNode(int v) { val = v;}DEFINE ListNodebuildList(int[] values)ListNode dummy = newListNode(0), tail = dummyfor (int v : values) {tail.next = newListNode(v); tail …RETURN dummy.nextDEFINE StringtoList(ListNode head)StringBuilder sb = newStringBuilder("[")while (head != null) {sb.append(head.val);head = head.next; i…RETURNsb.append("]").toString()DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE n = sc.nextInt()DEFINE [] a = new int[n]for (int i = 0; i <a.length; i++) a[i] =sc.nextInt()DEFINE m = sc.nextInt()DEFINE [] b = new int[m]for (int i = 0; i <b.length; i++) b[i] =sc.nextInt()System.out.println(toList(mergeTwoLists(buildList(a),buildList(b))))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/31

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits