Skip to the code
cf.
+25 XP

#190 Merge Sort a Linked Job Queue

medium

A build server keeps pending jobs in a singly linked list of ListNodes. Each val is a job's priority number, and lower numbers run first. The queue can hold tens of thousands of jobs, so an O(n²) sort is too slow.

Write sortQueue(head) that sorts the list ascending by val in O(n log n) time and returns the new head. Jobs with equal priority must keep their original order.

Example 1

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

Split into 4, 2 and 1, 3, sort each, then merge.

Example 2

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

Negative priorities run first.

Constraints

  • 0 <= number of nodes <= 50000
  • -10^5 <= 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).