Home › Company-wise questions › Microsoft › Merge Two Sorted Lists ← Microsoft bank
Microsoft · Question 16 · Linked Lists
Merge Two Sorted Lists Linked Lists Java code ⏱ O(n + m) 💾 O(n + m)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
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 Empty list returns the other one. 2 Attach 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 Flowchart Pseudocode
Time O(n + m)Space O(n + m)Loops 4Branches 3Returns 3source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
yes no START import java.util.* DEFINE class Main DEFINE static ListNode mergeTwoLists(ListNode l1, ListNode l2) if (l1 == null) return l2 if (l2 == null) return l1 if (l1.val < l2.val) l1.next = mergeTwoLists(l1.next, l2) RETURN l1 } else DEFINE class ListNode DEFINE val ListNode next ListNode(int v) { val = v; } DEFINE ListNode buildList(int[] values) ListNode dummy = new ListNode(0), tail = dummy for (int v : values) { tail.next = new ListNode(v); tail … RETURN dummy.next DEFINE String toList(ListNode head) StringBuilder sb = new StringBuilder("[") while (head != null) { sb.append(head.val); head = head.next; i… RETURN sb.append("]").toString() DEFINE static void main(String[] args) java.util.Scanner sc = new java.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← Q15 · Longest Substring Without Repeating Characters Q17 · Reverse Linked List → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →