MediumPythonJavaScriptTypeScript
Linked List — Sort a List (Merge Sort)
Data StructuresLinked ListSortingMerge Sort
solve(values) builds a singly linked list, sorts it in O(n log n) by re-linking
nodes, and returns the sorted values. Do not copy the values into an array and sort that.
Merge sort is the natural fit for linked lists: splitting needs no random access (find
the middle with slow / fast pointers and cut the list), and merging two sorted lists is
a pointer shuffle with no extra array.
Examples
solve([4,2,1,3]) → [1,2,3,4]
solve([-1,5,3,4,0]) → [-1,0,3,4,5]
solve([3,3,1,2,2]) → [1,2,2,3,3]Sample tests
Test #1Unsorted list
Input: [[4,2,1,3]]
Output: [1,2,3,4]
Test #2Negative values
Input: [[-1,5,3,4,0]]
Output: [-1,0,3,4,5]
Test #3Empty list
Input: [[]]
Output: []