Problem 725

Abstract / Summary

Split a linked list into k consecutive parts as evenly as possible.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
25 lines | 674 bytes | submitted September 6, 2023 | GitHub   4% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 71% (500k+ submissions).

Typical patterns to solve this problem:
  • Linked List
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.93 | σ = 1.21

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
35 links | 22 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

26 easy 21 medium 5 hard
53 solutions   September 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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