Skip to the code
cf.
+25 XP

#245 Sort a Chain of Events

medium

A replay tool receives user events as a linked list, but the network delivered them out of order. Each node's val is the event's timestamp.

Write sortEvents(head) that sorts the list by val from smallest to largest and returns the new head. Relink the existing nodes instead of copying them into an array, and aim for O(n log n) time.

Example 1

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

Sorted ascending.

Example 2

Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]

Negative timestamps sort first.

Constraints

  • The list has 0 to 5 * 10^4 nodes.
  • -10^5 <= node.val <= 10^5

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).