Split Linked List in Parts
1 approach, code in every language
Problem description
Given the head of a singly linked list and an integer k, break the list into k consecutive parts whose sizes are as balanced as possible. Any two parts may differ in length by at most one node, and earlier parts must be at least as long as later parts.
Some parts may be empty when k exceeds the number of nodes. Return an array of the k part heads in order, using an empty (null) reference for any empty part.
Example 1
Input: head = [1,2,3], k = 5
Output: [[1],[2],[3],[],[]]
There are only three nodes for five parts, so the first three parts hold one node each and the last two are empty.
Example 2
Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3
Output: [[1,2,3,4],[5,6,7],[8,9,10]]
Ten nodes over three parts gives base size three with one extra, so the first part gets the extra node.
Constraints
The number of nodes is in the range [0, 1000].0 <= Node.val <= 10001 <= k <= 50
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Dividing a Conveyor Into k Parts is our own problem on the technique behind Split Linked List in Parts: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free