#725
Split Linked List in Parts
MediumLinked ListTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution calculates the size of each part based on the total number of nodes and distributes them evenly. This approach only traverses the list once, making it efficient.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total number of nodes in the linked list.
- 2Step 2: Determine the size of each part and how many parts should have an extra node.
- 3Step 3: Traverse the list again, creating each part based on the calculated sizes.
solution.py27 lines
1# Full working Python code
2class ListNode:
3 def __init__(self, val=0, next=None):
4 self.val = val
5 self.next = next
6
7def splitListToParts(head, k):
8 total_nodes = 0
9 current = head
10 while current:
11 total_nodes += 1
12 current = current.next
13 part_size = total_nodes // k
14 extra_parts = total_nodes % k
15 parts = []
16 current = head
17 for i in range(k):
18 parts.append(current)
19 size = part_size + (1 if i < extra_parts else 0)
20 for j in range(size - 1):
21 if current:
22 current = current.next
23 if current:
24 next_part = current.next
25 current.next = None
26 current = next_part
27 return partsℹ
Complexity note: The complexity is O(n) because we traverse the linked list twice: once to count nodes and once to split them into parts.
- 1Understanding how to evenly distribute nodes is crucial for solving this problem.
- 2Recognizing the need to handle cases where k is greater than the number of nodes helps in preventing errors.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.