
Sponsored
Sponsored
This approach involves two main steps. First, traverse the linked list to determine its length. Then, decide how to split this length evenly across the k parts. Calculate the base size for each part and determine how many parts need an extra node.
Time Complexity: O(n) where n is the length of the linked list.
Space Complexity: O(k) for storing the resulting list parts.
1class ListNode:
2 def __init__(self, x):
3 self.val = x
4 self.next = None
5
6class Solution:
7 def splitListToParts(self, root: ListNode, k: int):
8 parts = [None] * k
9 length = 0
10 node = root
11 while node:
12 length += 1
13 node = node.next
14 partSize = length // k
15 extraNodes = length % k
16 node = root
17 for i in range(k):
18 parts[i] = node
19 currentPartSize = partSize + (1 if i < extraNodes else 0)
20 for j in range(currentPartSize - 1):
21 if node:
22 node = node.next
23 if node:
24 nextPart = node.next
25 node.next = None
26 node = nextPart
27 return partsThis Python solution follows the same logic: it calculates the length of the linked list, decides on the split sizes for each part, and uses list indexing to store the result. Python’s handling of list operations and iterations makes the code concise.
This approach involves iterating through the linked list and modifying the pointers to split the list directly into parts of calculated sizes based on total length and k. It ensures that the list splitting does not require additional passes, combining calculation and splitting in a single traversal.
Time Complexity: O(n) where n is the length of the linked list.
Space Complexity: O(k) for storing the resulting list pointers.
1
This Python solution combines looping and splitting in one traversal of the linked list. The use of divmod simplifies the calculation of base size and extra nodes needed, achieving a concise solution for the node management.