Python 0725.py
class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
length = 0
node = head
while node:
length += 1
node = node.next
result = []
while k > 0:
node = head
split = (length + k - 1) // k
for _ in range(split - 1): # process last differently
if node:
node = node.next
result.append(head)
if node:
head = node.next
node.next = None
k -= 1
length -= split
return result
Difficulty
and has an acceptance rate of about 71% (500k+ submissions).
Typical patterns to solve this problem:
- Linked List
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation splits a singly-linked list into k consecutive parts whose sizes differ by at most one element. The algorithm first measures the total number of nodes, then iteratively determines how many nodes belong to the current part, detaches that segment, and stores its head in the result collection. The process repeats until exactly k parts have been produced, padding with None when the original list is exhausted.
Step 1: Compute Length
The routine begins by walking the input list once to obtain its length.
length = 0
node = head
while node:
length += 1
node = node.next
This count is essential for calculating the base size of each part and for distributing any remainder nodes across the early parts.
Step 2: Determine Split Size
Inside the main loop, the size of the next part is computed with the expression
split = (length + k - 1) // k
The formula yields the ceiling of length / k, ensuring that any extra nodes are allocated to the first few parts. By recomputing split on each iteration, the algorithm automatically adapts to the decreasing length and k values, preserving the “at most one node difference” guarantee.
Step 3: Build Result List
For each part the algorithm advances a temporary pointer node exactly split-1 steps, leaving node positioned at the last node of the current segment (if such a node exists).
node = head
for _ in range(split - 1):
if node:
node = node.next
The head of the current segment (head) is appended to the result list. If node is not None, the segment is detached by advancing head to node.next and null-terminating the current part with node.next = None.
result.append(head)
if node:
head = node.next
node.next = None
Finally, the counters k and length are decremented to reflect the consumption of one part and its nodes.
k -= 1
length -= split
When the original list runs out of nodes, head becomes None; subsequent iterations still append None to result, guaranteeing exactly k entries.
Edge Cases Handled
When the input list is empty (head is None), the initial length calculation yields zero. The split size formula then evaluates to zero for every iteration, causing the inner loop to skip and the algorithm to append None repeatedly, producing a list of k None values.
If k exceeds the number of nodes, the ceiling division ensures that the first length parts receive one node each (split becomes 1), while the remaining parts receive zero nodes (split becomes 0). The detachment logic gracefully handles a node that is None, leaving head unchanged (None) and appending None for the empty parts.
When k equals one, the split size equals the total length, the inner loop walks to the last node, and the entire list is returned as a single part without modification.
When k equals the list length, each part receives exactly one node; the inner loop runs zero times, and the detachment step isolates each node individually.
Performance Optimizations
The algorithm performs a single pass to compute the list length, followed by a second pass that visits each node exactly once while constructing the parts. By reusing the original node objects and only adjusting next pointers, it avoids allocating new list nodes or auxiliary data structures beyond the result list.
The use of integer arithmetic (length + k - 1) // k eliminates the need for conditional logic to distribute remainder nodes, allowing the split size to be derived in constant time per iteration.
Detaching each segment in place (node.next = None) prevents the need for a separate traversal to truncate the segment, thereby reducing overhead. The decrement of length by split after each part ensures that the subsequent split size calculation works with the remaining unprocessed nodes, keeping the loop’s work proportional to the number of nodes rather than to k times the list length.
Overall, the implementation achieves linear time behavior relative to the number of nodes while using only O(k) additional space for the result container.
ELI5 - Simplified Explanation
Imagine a long train made of many colorful toy cars hooked together in a line. This code is like a helper whose job is to take that long train apart and bundle the cars into smaller, shorter trains so there are exactly as many groups as a requested number.
First, the helper walks from the very front of the train all the way to the back to count every single car. This tells the helper how many cars are in total.
Next, the helper starts making smaller groups. To figure out how many cars should go into the first bundle, the helper does a bit of math to divide the total number of cars by the number of bundles needed. If there are extra cars left over, the helper makes sure the first few bundles get one extra car so everything is shared as evenly as possible.
The helper reaches out to grab the cars for the current group. Once that group is filled up, the helper carefully unhooks the last car in that group from the rest of the train. This creates a clean break so the group can stand on its own.
After unhooking a group, the helper saves it to a list and moves on to the next section of the train. The process repeats, with the helper counting how many cars are left and deciding the size for the next bundle, until every car has been placed into one of the groups. By the end, all the cars are neatly separated into the desired number of smaller trains.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 61: Rotate List
- problem 328: Odd Even Linked List
Solved On The Same Day
- problem 175: Combine Two Tables
- problem 181: Employees Earning More Than Their Managers
- problem 182: Duplicate Emails
- problem 183: Customers Who Never Order
- problem 193: Valid Phone Numbers
- problem 196: Delete Duplicate Emails
- problem 197: Rising Temperature
- problem 203: Remove Linked List Elements
- problem 511: Game Play Analysis I
- problem 577: Employee Bonus
- problem 584: Find Customer Referee
- problem 586: Customer Placing the Largest Number of Orders
- problem 595: Big Countries
- problem 596: Classes With at Least 5 Students
- problem 607: Sales Person
- problem 610: Triangle Judgement
- problem 619: Biggest Single Number
- problem 620: Not Boring Movies
- problem 627: Swap Sex of Employees
- problem 1050: Actors and Directors Who Cooperated At Least Three Times
- problem 1068: Product Sales Analysis I
- problem 1075: Project Employees I
- problem 1084: Sales Analysis III
- problem 1141: User Activity for the Past 30 Days I
- problem 1148: Article Views I
- problem 1179: Reformat Department Table
- problem 176: Second Highest Salary
- problem 177: Nth Highest Salary
- problem 178: Rank Scores
- problem 180: Consecutive Numbers
- problem 184: Department Highest Salary
- problem 192: Word Frequency
- problem 194: Transpose File
- problem 550: Game Play Analysis IV
- problem 570: Managers with at Least 5 Direct Reports
- problem 585: Investments in 2016
- problem 602: Friend Requests II: Who Has the Most Friends
- problem 608: Tree Node
- problem 626: Exchange Seats
- problem 1045: Customers Who Bought All Products
- problem 1070: Product Sales Analysis III
- problem 1164: Product Price at a Given Date
- problem 1174: Immediate Food Delivery II
- problem 1193: Monthly Transactions I
- problem 1204: Last Person to Fit in the Bus
- problem 1321: Restaurant Growth
- problem 1393: Capital Gain/Loss
- problem 174: Dungeon Game
- problem 185: Department Top Three Salaries
- problem 218: The Skyline Problem
- problem 262: Trips and Users
- problem 601: Human Traffic of Stadium
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality