Merge two Sorted Lists

Linked-List FAQs (Hard) Hard
  • Fun Fact: The problem of merging two sorted linked lists, as stated above, is a heart of many applications that deal with sorted data
  • For example, in GitHub, when two developers work on the same code base (their own linked lists of code), and after they have made their changes, GitHub has to 'merge' the two versions into one sorted list (code base) while keeping the modifications from both developers intact
  • This problem simulates that scenario
  • Such algorithms also underpin 'merge sort', a commonly used sorting algorithm in computer programming
  • Similarly, database management systems often use such concepts when merging data coming from multiple sources

Given the heads of two linked lists, list1 and list2, where each linked list has its elements sorted in non-decreasing order, merge them into a single sorted linked list and return the head of the merged linked list.

Examples:

Input: list1 = head -> 2 -> 4 -> 7 -> 9, list2 = head -> 1 -> 2 -> 5 -> 6

Output: head -> 1 -> 2 -> 2 -> 4 -> 5 -> 6 ->7 -> 9

Explanation: head -> 1 -> 2 -> 2 -> 4 -> 5 -> 6 ->7 -> 9, the underlined nodes come from list2, the others come from list1.

Input: list1 = head -> 1 -> 2 -> 3 -> 4, list2 = head -> 5 -> 6 -> 10

Output: head -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 10

Explanation: head -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 10, the underlined nodes come from list2, the others come from list1.

Input: list1 = head -> 0 -> 2, list2 = head -> 1 -> 3 -> 5 -> 6

Constraints

  • 0 <= number of nodes in list1, list2 <= 5 * 104
  • -104 <= ListNode.val <= 104
  • list1 and list2 are sorted in non-decreasing order.

Hints

  • A brute-force approach would: Extract all nodes into an array (O(n + m) space). Sort the array (O((n + m) log(n + m)) time). Reconstruct the linked list (O(n + m) time).
  • Use two pointers (p1 for list1 and p2 for list2). Compare nodes and attach the smaller one to the result list. Advance the pointer of the list from which the node was taken. Once one list is exhausted, attach the remaining nodes from the other list.

Company Tags

Johnson & Johnson IBM Salesforce Walmart NVIDIA Cloudflare Morgan Stanley Robinhood GE Healthcare Alibaba KPMG Epic Systems Databricks Bain & Company Zoho Chewy HCL Technologies Swiggy Intel Activision Blizzard Zynga OYO Rooms Philips Healthcare Epic Games Oracle Google Microsoft Amazon Meta Apple Netflix Adobe