InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Sort List

medium Original ↗ 00:00

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.

A linked list has no random access, so array-sorting techniques that depend on indexing (quickselect partitions, heapify) don’t transfer directly. The LeetCode follow-up, 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 never need random access, only sequential walks and splicing? That one fits a linked list naturally.
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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug