KatInterview

725. Split Linked List in Parts

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

The problem asks us to split a given singly linked list into k consecutive parts. The key constraints are that the lengths of these parts should be as equal as possible (differing by at most 1), and parts that appear earlier in the list should have a size greater than or equal to later parts. This implies a distribution problem: given N nodes and k parts, how to distribute the nodes evenly.

Solution

Split Linked List in Parts 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 splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
        # Step 1: Find the length of the linked list.
        length = 0
        current = head
        while current:
            length += 1
            current = current.next

        # Step 2: Calculate the size of each part.
        quotient, remainder = divmod(length, k)

        # Step 3: Split the list into k parts.
        result = []
        current = head
        for i in range(k):
            result.append(current) # The head of the current part

            # Determine the size of the current part.
            # The first 'remainder' parts get an extra node.
            part_size = quotient + (1 if i < remainder else 0)
            
            if current and part_size > 0:
                # Traverse to the end of the current part.
                # We need to move part_size - 1 steps to reach the last node.
                for _ in range(part_size - 1):
                    current = current.next
                
                # Detach the current part from the rest of the list.
                next_head = current.next # The head of the next part
                current.next = None      # Terminate the current part
                current = next_head      # Move to the start of the next part
        
        return result

Split Linked List in Parts 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[] splitListToParts(ListNode head, int k) {
        // Step 1: Find the length of the linked list.
        int length = 0;
        ListNode current = head;
        while (current != null) {
            length++;
            current = current.next;
        }

        // Step 2: Calculate the size of each part.
        int quotient = length / k; // Base size of each part
        int remainder = length % k;  // Number of parts that have an extra node

        // Step 3: Split the list into k parts.
        ListNode[] result = new ListNode[k];
        current = head;
        for (int i = 0; i < k; i++) {
            result[i] = current; // The head of the current part

            // Determine the size of the current part.
            // The first 'remainder' parts get an extra node.
            int partSize = quotient + (i < remainder ? 1 : 0);

            if (current != null && partSize > 0) {
                // Traverse to the end of the current part.
                // We need to move partSize - 1 steps to reach the last node.
                for (int j = 0; j < partSize - 1; j++) {
                    current = current.next;
                }

                // Detach the current part from the rest of the list.
                ListNode nextHead = current.next; // The head of the next part
                current.next = null;            // Terminate the current part
                current = nextHead;                 // Move to the start of the next part
            }
        }
        
        return result;
    }
}

Split Linked List in Parts 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:
    vector<ListNode*> splitListToParts(ListNode* head, int k) {
        // Step 1: Find the length of the linked list.
        int length = 0;
        ListNode* current = head;
        while (current != nullptr) {
            length++;
            current = current->next;
        }

        // Step 2: Calculate the size of each part.
        int quotient = length / k; // Base size of each part
        int remainder = length % k;  // Number of parts that have an extra node

        // Step 3: Split the list into k parts.
        vector<ListNode*> result(k);
        current = head;
        for (int i = 0; i < k; ++i) {
            result[i] = current; // The head of the current part

            // Determine the size of the current part.
            // The first 'remainder' parts get an extra node.
            int partSize = quotient + (i < remainder ? 1 : 0);

            if (current != nullptr && partSize > 0) {
                // Traverse to the end of the current part.
                // We need to move partSize - 1 steps to reach the last node.
                for (int j = 0; j < partSize - 1; ++j) {
                    current = current->next;
                }

                // Detach the current part from the rest of the list.
                ListNode* nextHead = current->next; // The head of the next part
                current->next = nullptr;            // Terminate the current part
                current = nextHead;                 // Move to the start of the next part
            }
        }
        
        return result;
    }
};

Split Linked List in Parts 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 splitListToParts(head: ListNode | null, k: number): Array<ListNode | null> {
    // Step 1: Find the length of the linked list.
    let length = 0;
    let current: ListNode | null = head;
    while (current) {
        length++;
        current = current.next;
    }

    // Step 2: Calculate the size of each part.
    const quotient = Math.floor(length / k); // Base size of each part
    const remainder = length % k; // Number of parts that have an extra node

    // Step 3: Split the list into k parts.
    const result: Array<ListNode | null> = new Array(k).fill(null);
    current = head;
    for (let i = 0; i < k; i++) {
        result[i] = current; // The head of the current part

        // Determine the size of the current part.
        // The first 'remainder' parts get an extra node.
        const partSize = quotient + (i < remainder ? 1 : 0);

        if (current && partSize > 0) {
            // Traverse to the end of the current part.
            // We need to move partSize - 1 steps to reach the last node.
            for (let j = 0; j < partSize - 1; j++) {
                if (current) {
                    current = current.next;
                }
            }
            
            // Detach the current part from the rest of the list.
            if (current) {
                const nextHead = current.next; // The head of the next part
                current.next = null;          // Terminate the current part
                current = nextHead;           // Move to the start of the next part
            }
        }
    }
    
    return result;
};

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.