#148

Sort List

Medium Merge sort on a linked list

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Sort a singly linked list in O(n log n) time.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: sort a linked list in O(n log n).

Why this works: merge sort only needs to walk forward: find the middle, cut, sort both halves, merge.

Example: 4 → 2 → 1 → 3

halves 4→2 and 1→3 → sorted 2→4 and 1→3merge → 1→2→3→4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Not cutting the list (setting mid.next = null), which makes the recursion never shrink.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n).
  • Space: O(log n) recursion stack.
Topic: Sorting
🎬 Episodes 24–28: video coming soon