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 <= 50See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI