Back to DSA

Sort List

hard
Acceptance: 40%
Linked List

Sort a singly linked list in ascending order. Aim for O(n log n) time complexity. Return the head of the sorted list.

Examples

Example 1:
Input:head = [6,1,4,2]
Output:[1,2,4,6]
Example 2:
Input:head = [0,9,-3,5,1]
Output:[-3,0,1,5,9]

Hints

00:00
class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode mid = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(mid);
        return merge(left, right);
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0), curr = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) { curr.next = l1; l1 = l1.next; }
            else { curr.next = l2; l2 = l2.next; }
            curr = curr.next;
        }
        curr.next = (l1 != null) ? l1 : l2;
        return dummy.next;
    }
}
Time complexityO(n log n)
Space complexityO(log n)