InterviewPrepKit

Home / Coding / Linked List

Sort List

medium Original β†—
Solving tips
  • Merge sort is the natural fit: it needs only sequential access (split + merge), unlike quicksort/heapsort which want random access.
  • Top-down: find the middle with slow/fast pointers, cut with slow.next = None, recurse on each half, then merge two sorted lists.
  • Starting fast at head.next keeps even-length splits balanced and avoids infinite recursion on a 2-node list.
  • Target O(n log n) time; top-down is O(log n) stack, but bottom-up merge sort (doubling run length) achieves the true O(1)-space follow-up.

Problem

You are given the head of a singly-linked list. Rearrange the nodes so that the list is sorted in ascending order by node value, and return the head of the sorted list.

The catch is the data structure: a linked list has no random access, so array sorting tricks (quickselect partitions by index, heapify by index arithmetic) don’t transfer directly. The follow-up LeetCode poses β€” and the version interviewers usually want β€” is to sort in O(n log n) time using O(1) extra memory.

Examples

  • Input: head = [4, 2, 1, 3] β†’ Output: [1, 2, 3, 4] The four nodes are relinked into ascending order.
  • Input: head = [-1, 5, 3, 4, 0] β†’ Output: [-1, 0, 3, 4, 5] Negative values are allowed; they sort like any other integer.
  • Input: head = [] β†’ Output: [] An empty list is already sorted.

Constraints

  • Number of nodes is in [0, 5 * 10^4] β€” an O(n^2) sort (insertion sort on the list) is too slow.
  • -10^5 <= Node.val <= 10^5
  • Follow-up: O(n log n) time and O(1) space (which rules out both β€œdump into an array” and recursion’s stack).

Think about it first

Hint 1 Which O(n log n) sorts do you know? Which of them never needs random access β€” only sequential walks and splicing? That one is a natural fit for linked lists.
Hint 2 Merge sort: split the list into two halves, sort each, merge. On a linked list you can find the middle with a slow/fast pointer pair, and merging two sorted lists is a classic O(1)-space operation.
Hint 3 Recursion costs O(log n) stack. To hit true O(1) space, run merge sort bottom-up: first merge runs of length 1 into runs of length 2, then 2 into 4, and so on, doubling the run length each pass until one run covers the whole list.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.