148. Sort List

Medium

Problem:

Sort the linked list in O(nlogn)O(nlogn) time complexity.

https://leetcode.com/problems/sort-listarrow-up-right

Solution:

Merge Sort

circle-exclamation
  1. For the divide-and-conquer strategy of merge sort, the list should be split in the middle. However, since the total length of a linked list is unknown, we need to employ the Runner technique.

  2. Using three variables, half, slow, and fast, move slow one step at a time and fast two steps at a time. When fast reaches the end, slow will be in the middle. At this point, set half to the value right before slow and cut off the linked list relationship based on the position of half.

  3. Finally, compare the sizes of the divided items and merge them back together in a sorted manner.

A practical method using built-in functions

If you need to write algorithms on a whiteboard during an interview, you should avoid this approach.

Last updated