Imagine you have a long chain of connected elements, and you need to divide it fairly into k separate groups. This is exactly what we're doing with a linked list!
Given the head of a singly linked list and an integer k, your task is to split the linked list into k consecutive parts. The challenge is to make the split as fair as possible:
- Equal distribution: No two parts should differ in size by more than one node
- Front-heavy: If sizes can't be perfectly equal, earlier parts should be larger
- Order preserved: Maintain the original order of nodes
- Null parts allowed: Some parts can be empty if
kis larger than the list length
Return an array of k ListNode heads, where each head points to the start of one part.
Example: A list of 10 nodes split into 3 parts would create parts of sizes [4, 3, 3] - the first part gets the extra node.
Input & Output
Visualization
Time & Space Complexity
We traverse n nodes to count, then for each of k parts, we may traverse up to n nodes again to reach the starting position
Only using constant extra space for variables, not counting the output array
Constraints
-
The number of nodes in the list is in the range
[0, 1000] -
1 β€ k β€ 50 -
0 β€ Node.val β€ 1000 - Follow-up: Can you solve this without modifying the original list structure?