Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - First calculate length and then split the list
- First, we calculate the total length of the linked list by traversing it with a while loop. We use a helper function
size
to find the length of the linked list, from Find the length of the linked list. - We calculate two key values:
m
: The minimum guaranteed size of each part, found by dividing the total length byk
.r
: The number of extra nodes to distribute among the firstr
parts, which is the remainder of the division.
- We use the
curr
pointer to traverse the linked list. We then loop through each part:- Store the current node as the start of the current part in the
parts
array. - Traverse
m + 1
nodes if there are remaining extra nodes (r > 0
for the firstr
parts); otherwise, traversem
nodes. - After traversing the desired number of nodes, disconnect the current part from the rest of the list by setting
curr.next
tonull
. Then movecurr
to the next part’s first node.
- Store the current node as the start of the current part in the
- Return
parts
.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
Complexity
- ⏰ Time complexity:
O(max(n, k))
wheren
is the length of the linked list - 🧺 Space complexity:
O(n)