Sort List

Medium

Topics
Linked ListSortingMerge SortDivide and Conquer

Given the head of a linked list, return the list sorted in ascending order.

Example 1

before4213null
sorted1234null
first half after splitting
The list must come back in ascending order. The nodes themselves are relinked rather than having their values shuffled, and a list offers no random access — reaching the middle means walking there — which is what separates this from sorting an array.
Linked list values from head to tail.
Input:  head = [4,2,1,3]
Output: [1,2,3,4]

Example 2

before-15340null
sorted-10345null
first half after splitting
Input:  head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]

Constraints

  • 0 <= number of nodes <= 5*10^4
  • -10^5 <= Node.val <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Sorting a linked list in O(n log n) without random access points at merge sort: splitting a list is cheap, and merging two sorted lists is a pointer walk. The usual presentation is top-down — find the middle, recurse, merge — which is O(log n) call frames.

The shown solution is bottom-up, which removes the recursion entirely. Merge adjacent runs of length 1, then of length 2, then 4, doubling until the run length covers the list. Same O(n log n), same stability, but O(1) auxiliary space and no stack-depth exposure at the stated bound of 5×10⁴ nodes.

Collecting the values into an array, sorting that, and writing them back is also O(n log n) and is a legitimate pragmatic answer — but it costs O(n) space and never touches a pointer, so it sidesteps everything this problem examines.

Approach

  1. Count the nodes to get n, and put a dummy in front so the head can change.
  2. For each width in 1, 2, 4, ... while width < n, walk the list taking two consecutive runs of that length.
  3. cut(head, k) keeps k nodes, detaches the rest, and returns the remainder — so two cuts isolate the left run, the right run, and the position to resume from.
  4. Merge the two runs onto the tail built so far, and carry the new tail forward as the next prev.
  5. Return dummy.next.

Dry Run

input  4 -> 2 -> 1 -> 3        n = 4

width 1   runs (4)(2) and (1)(3)
          merge -> 2 -> 4,  then 1 -> 3
          list is now  2 -> 4 -> 1 -> 3

width 2   runs (2 4)(1 3)
          merge -> 1 -> 2 -> 3 -> 4

width 4   not less than n, stop

answer  1 -> 2 -> 3 -> 4

verified against sorted() on 300 random lists up to length 60, plus
  []            -> []
  [1]           -> [1]
  [5,5,5]       -> [5,5,5]       equal keys keep input order
  [-1,5,3,4,0]  -> [-1,0,3,4,5]

Complexity

  • Time — O(n log n): there are log₂n doubling rounds and each round walks and merges every node once.
  • Space — O(1): a dummy and a few pointers. Nothing is copied and there is no recursion, which is the whole reason to prefer bottom-up here.
  • The top-down version is the same time bound but O(log n) stack frames; the collect-and-sort version is O(n) space.

Common Pitfalls

  • Sorting the values and writing them back. It produces a correctly ordered list and it is what the page used to ship, but it neither merge-sorts nor relinks, so it answers a different question than the one the problem tags advertise.
  • Using < rather than <= in the merge. Merge sort's stability depends on preferring the left run when keys tie; with < equal elements swap order.
  • Forgetting to null-terminate when cutting. If cut does not sever head.next, the "two runs" are still one list and the merge walks past its own boundary.
  • Failing to advance the tail to the actual end after a merge. When one run is exhausted the remainder is attached wholesale, so the new tail is at the end of that remainder, not where the comparison loop stopped.
  • Quicksort on a linked list. Partitioning is fine but the pivot choice has no random access, so the worst case is O(n²) with no cheap mitigation.
  • Finding the middle with a slow and fast pointer in the top-down version and forgetting to cut the first half loose, which recurses on the whole list forever.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def sortList(self, head):
        if not head or not head.next:
            return head
        n = 0
        cur = head
        while cur:
            n += 1
            cur = cur.next
        # Bottom-up merge sort: merge runs of 1, then 2, then 4 ... No recursion,
        # so no O(log n) call stack, and the nodes themselves are relinked.
        dummy = ListNode(0, head)
        width = 1
        while width < n:
            prev = dummy
            cur = dummy.next
            while cur:
                left = cur
                right = self._cut(left, width)
                cur = self._cut(right, width)
                prev = self._merge(left, right, prev)
            width *= 2
        return dummy.next

    def _cut(self, head, k):
        """Keep k nodes from head, detach the rest and return the remainder."""
        while k > 1 and head:
            head = head.next
            k -= 1
        if not head:
            return None
        rest = head.next
        head.next = None
        return rest

    def _merge(self, a, b, tail):
        """Append the merge of a and b after tail; return the new tail."""
        cur = tail
        while a and b:
            if a.val <= b.val:        # <= keeps the sort stable
                cur.next = a
                a = a.next
            else:
                cur.next = b
                b = b.next
            cur = cur.next
        cur.next = a if a else b
        while cur.next:
            cur = cur.next
        return cur
Asked at Lyft
SensAI
Beta
Tap the mic to stop voice mode