KatInterview

148. Sort List

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Bottom-up Merge Sort

The problem asks us to sort a linked list with O(n log n) time complexity and O(1) space complexity. These constraints are a strong hint towards using a bottom-up merge sort algorithm.

Solution

Sort List in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # Base case: 0 or 1 node
        if not head or not head.next:
            return head

        # 1. Get the length of the list
        length = 0
        node = head
        while node:
            length += 1
            node = node.next

        # Dummy node to simplify list manipulations
        dummy = ListNode(0, head)

        # 2. Bottom-up merge sort
        # k is the size of the sublists to be merged
        k = 1
        while k < length:
            tail = dummy
            curr = dummy.next
            while curr:
                # Get the first sublist
                list1 = curr
                # Split the list to get the second sublist
                list2 = self.split(list1, k)
                # The rest of the list starts after list2
                curr = self.split(list2, k)
                
                # Merge list1 and list2
                merged_head, merged_tail = self.merge(list1, list2)
                
                # Append the merged list to the sorted part
                tail.next = merged_head
                tail = merged_tail
            
            k <<= 1
        
        return dummy.next

    def split(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        """Splits the list after k nodes and returns the head of the second part."""
        if not head:
            return None
        curr = head
        # Move k-1 steps to find the k-th node
        for _ in range(k - 1):
            if not curr:
                break
            curr = curr.next
        
        if not curr:
            return None
        
        second_part = curr.next
        curr.next = None  # Cut the list
        return second_part

    def merge(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> tuple[Optional[ListNode], Optional[ListNode]]:
        """Merges two sorted lists and returns the head and tail of the merged list."""
        dummy_head = ListNode(0)
        tail = dummy_head
        while list1 and list2:
            if list1.val < list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next
            tail = tail.next
        
        # Append the remaining nodes
        tail.next = list1 or list2
        
        # Find the new tail
        while tail.next:
            tail = tail.next
            
        return dummy_head.next, tail

Sort List in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        // Base case: 0 or 1 node
        if (head == null || head.next == null) {
            return head;
        }

        // 1. Get the length of the list
        int length = 0;
        ListNode node = head;
        while (node != null) {
            length++;
            node = node.next;
        }

        // Dummy node to simplify list manipulations
        ListNode dummy = new ListNode(0, head);

        // 2. Bottom-up merge sort
        // k is the size of the sublists to be merged
        for (int k = 1; k < length; k <<= 1) {
            ListNode tail = dummy;
            ListNode curr = dummy.next;
            while (curr != null) {
                // Get the first sublist
                ListNode list1 = curr;
                // Split the list to get the second sublist
                ListNode list2 = split(list1, k);
                // The rest of the list starts after list2
                curr = split(list2, k);
                
                // Merge list1 and list2
                ListNode[] merged = merge(list1, list2);
                
                // Append the merged list to the sorted part
                tail.next = merged[0];
                tail = merged[1];
            }
        }
        
        return dummy.next;
    }

    // Splits the list after k nodes and returns the head of the second part.
    private ListNode split(ListNode head, int k) {
        if (head == null) return null;
        ListNode curr = head;
        // Move k-1 steps to find the k-th node
        for (int i = 1; i < k && curr != null; i++) {
            curr = curr.next;
        }
        if (curr == null) return null;
        
        ListNode secondPart = curr.next;
        curr.next = null; // Cut the list
        return secondPart;
    }

    // Merges two sorted lists and returns an array containing the head and tail.
    private ListNode[] merge(ListNode list1, ListNode list2) {
        ListNode dummyHead = new ListNode(0);
        ListNode tail = dummyHead;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                tail.next = list1;
                list1 = list1.next;
            } else {
                tail.next = list2;
                list2 = list2.next;
            }
            tail = tail.next;
        }
        
        // Append the remaining nodes
        tail.next = (list1 != null) ? list1 : list2;
        
        // Find the new tail
        while (tail.next != null) {
            tail = tail.next;
        }
        
        return new ListNode[]{dummyHead.next, tail};
    }
}

Sort List in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        // Base case: 0 or 1 node
        if (!head || !head->next) {
            return head;
        }

        // 1. Get the length of the list
        int length = 0;
        ListNode* node = head;
        while (node) {
            length++;
            node = node->next;
        }

        // Dummy node to simplify list manipulations
        ListNode* dummy = new ListNode(0, head);

        // 2. Bottom-up merge sort
        // k is the size of the sublists to be merged
        for (int k = 1; k < length; k <<= 1) {
            ListNode* tail = dummy;
            ListNode* curr = dummy->next;
            while (curr) {
                // Get the first sublist
                ListNode* list1 = curr;
                // Split the list to get the second sublist
                ListNode* list2 = split(list1, k);
                // The rest of the list starts after list2
                curr = split(list2, k);
                
                // Merge list1 and list2
                auto [merged_head, merged_tail] = merge(list1, list2);
                
                // Append the merged list to the sorted part
                tail->next = merged_head;
                tail = merged_tail;
            }
        }
        
        ListNode* sorted_head = dummy->next;
        delete dummy;
        return sorted_head;
    }

private:
    // Splits the list after k nodes and returns the head of the second part.
    ListNode* split(ListNode* head, int k) {
        if (!head) return nullptr;
        ListNode* curr = head;
        // Move k-1 steps to find the k-th node
        for (int i = 1; i < k && curr; i++) {
            curr = curr->next;
        }
        if (!curr) return nullptr;
        
        ListNode* second_part = curr->next;
        curr->next = nullptr; // Cut the list
        return second_part;
    }

    // Merges two sorted lists and returns the head and tail of the merged list.
    pair<ListNode*, ListNode*> merge(ListNode* list1, ListNode* list2) {
        ListNode dummy_head(0);
        ListNode* tail = &dummy_head;
        while (list1 && list2) {
            if (list1->val < list2->val) {
                tail->next = list1;
                list1 = list1->next;
            } else {
                tail->next = list2;
                list2 = list2->next;
            }
            tail = tail->next;
        }
        
        // Append the remaining nodes of whichever list is not empty
        tail->next = (list1) ? list1 : list2;
        
        // Find the new tail of the merged list
        while (tail->next) {
            tail = tail->next;
        }
        
        return {dummy_head.next, tail};
    }
};

Sort List in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function sortList(head: ListNode | null): ListNode | null {
    // Base case: 0 or 1 node
    if (!head || !head.next) {
        return head;
    }

    // 1. Get the length of the list
    let length = 0;
    let node: ListNode | null = head;
    while (node) {
        length++;
        node = node.next;
    }

    // Dummy node to simplify list manipulations
    const dummy = new ListNode(0, head);

    // 2. Bottom-up merge sort
    // k is the size of the sublists to be merged
    for (let k = 1; k < length; k <<= 1) {
        let tail: ListNode | null = dummy;
        let curr: ListNode | null = dummy.next;
        while (curr) {
            // Get the first sublist
            let list1: ListNode | null = curr;
            // Split the list to get the second sublist
            let list2: ListNode | null = split(list1, k);
            // The rest of the list starts after list2
            curr = split(list2, k);
            
            // Merge list1 and list2
            const [mergedHead, mergedTail] = merge(list1, list2);
            
            // Append the merged list to the sorted part
            if (tail) {
                tail.next = mergedHead;
            }
            tail = mergedTail;
        }
    }
    
    return dummy.next;
}

// Splits the list after k nodes and returns the head of the second part.
function split(head: ListNode | null, k: number): ListNode | null {
    if (!head) return null;
    let curr: ListNode | null = head;
    // Move k-1 steps to find the k-th node
    for (let i = 1; i < k && curr; i++) {
        curr = curr.next;
    }
    if (!curr) return null;
    
    const secondPart = curr.next;
    curr.next = null; // Cut the list
    return secondPart;
}

// Merges two sorted lists and returns a tuple with the head and tail.
function merge(list1: ListNode | null, list2: ListNode | null): [ListNode | null, ListNode | null] {
    const dummyHead = new ListNode(0);
    let tail: ListNode = dummyHead;
    while (list1 && list2) {
        if (list1.val < list2.val) {
            tail.next = list1;
            list1 = list1.next;
        } else {
            tail.next = list2;
            list2 = list2.next;
        }
        tail = tail.next;
    }
    
    // Append the remaining nodes
    tail.next = list1 ? list1 : list2;
    
    // Find the new tail
    while (tail.next) {
        tail = tail.next;
    }
    
    return [dummyHead.next, tail];
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.