Given the head
of a singly linked list and an integer k
, split the linked list into k
consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return an array of the k
parts.
Example 1:
Input: head = [1,2,3], k = 5 Output: [[1],[2],[3],[],[]] Explanation: The first element output[0] has output[0].val = 1, output[0].next = null. The last element output[4] is null, but its string representation as a ListNode is [].
Example 2:
Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3 Output: [[1,2,3,4],[5,6,7],[8,9,10]] Explanation: The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
Constraints:
- The number of nodes in the list is in the range
[0, 1000]
. 0 <= Node.val <= 1000
1 <= k <= 50
Approach 01:
-
C++
-
Python
/** * 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: Count the total number of nodes in the linked list int totalNodes = 0; ListNode* current = head; while (current) { totalNodes++; current = current->next; } // Step 2: Determine the size of each part and the extra nodes int nodesPerPart = totalNodes / k; int extraNodes = totalNodes % k; // Nodes to be distributed in the first 'extraNodes' parts // Step 3: Initialize result list vector<ListNode*> result(k, nullptr); current = head; // Step 4: Split the linked list into parts for (int i = 0; i < k; ++i) { ListNode* partHead = current; int partSize = nodesPerPart + (i < extraNodes ? 1 : 0); // Determine the size of the current part // Traverse 'partSize' nodes for the current part for (int j = 0; j < partSize - 1 && current; ++j) { current = current->next; } // If there are nodes in the current part, detach it from the rest if (current) { ListNode* nextPartHead = current->next; current->next = nullptr; // End the current part current = nextPartHead; // Move to the next part's head } // Append the head of the current part to the result result[i] = partHead; } return result; } };
class Solution: def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]: # Step 1: Count the total number of nodes in the linked list totalNodes = 0 current = head while current: totalNodes += 1 current = current.next # Step 2: Determine the size of each part and the extra nodes nodesPerPart = totalNodes // k extraNodes = totalNodes % k # Nodes to be distributed in the first 'extraNodes' parts # Step 3: Initialize result list result = [] current = head # Step 4: Split the linked list into parts for i in range(k): partHead = current partSize = nodesPerPart + (1 if i < extraNodes else 0) # Determine the size of the current part # Traverse 'partSize' nodes for the current part for j in range(partSize - 1): if current: current = current.next # If there are nodes in the current part, detach it from the rest if current: nextPartHead = current.next current.next = None # End the current part current = nextPartHead # Move to the next part's head # Append the head of the current part to the result result.append(partHead) # Step 5: If there are fewer nodes than k, append None for the remaining parts while len(result) < k: result.append(None) return result
Time Complexity
- Main Function
splitListToParts
:The function performs the following steps:
- Step 1: Counts the total number of nodes in the linked list by iterating over the list once. This takes \( O(n) \) time, where \( n \) is the total number of nodes in the linked list.
- Step 2: Computes the size of each part and the number of extra nodes. This is an \( O(1) \) operation.
- Step 3: Splits the linked list into parts. This involves iterating through the linked list again, which takes \( O(n) \) time.
Therefore, the overall time complexity of the solution is \( O(n) \).
Space Complexity
- Auxiliary Space:
The space complexity is \( O(k) \), where \( k \) is the number of parts the linked list is split into. This is due to the storage of the resulting vector of linked list heads. The algorithm does not use any additional space that scales with the input size beyond the output storage.