FrontendInterviews.dev

Loading problem…

298. Merge Two Sorted Lists

Easyβ€’
Acceptance: 100.00%
β€’
πŸ”“3/3 Pro unlocks today

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

This is the fundamental merge operation used in merge sort and is a building block for merging K sorted lists.

Requirements

1. Basic Functionality

  • Merge two sorted linked lists into one sorted list
  • Handle empty lists
  • Maintain sorted order

Example Usage

// list1: 1 β†’ 2 β†’ 4
// list2: 1 β†’ 3 β†’ 4
// merged: 1 β†’ 1 β†’ 2 β†’ 3 β†’ 4 β†’ 4

Real-World Context

  • Merge sort: Core operation in the merge sort algorithm
  • Database merging: Combining sorted query results from different shards
  • Log aggregation: Merging sorted log entries from multiple servers

Constraints

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.