A singly linked list starts at head, and you are given a number k. Break the list into exactly k consecutive pieces and return them as an array of k list heads.
The pieces must be as even as possible: any two sizes differ by at most one, and a piece never holds fewer nodes than a piece after it. Keep the nodes in their original order. When there are fewer nodes than k, the last pieces are empty (null).
Example 1
Input: head = [5,1,7,3,2], k = 3 Output: [[5,1],[7,3],[2]] Why: 5 nodes in 3 parts: sizes 2, 2, 1
2 more examples and the constraints
Example 2
Input: head = [4,9], k = 4 Output: [[4],[9],[],[]] Why: only 2 nodes, so 2 parts stay empty
Example 3
Input: head = [], k = 2 Output: [[],[]] Why: an empty list gives k empty parts
Constraints
- 0 ≤ number of nodes ≤ 1,000
- 0 ≤ node values ≤ 1,000
- 1 ≤ k ≤ 50
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy values, rebuild partsO(n + k)
- Count, then cut in placeO(n + k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Extra memory for 1,000 nodes | Verdict |
|---|---|---|---|
| Copy values, rebuild parts | O(n + k) | Works; copies every node | |
| Count, then cut in place | O(n + k) | Best; reuses the original nodes |
n = number of nodes, k = number of parts. Time is the same; the bars compare extra memory.
Edge cases to test
- Fewer nodes than k.
size = 0, so the firstnparts get one node each and the rest are null. - Empty list. Every one of the
kparts is null. - k = 1. The whole list is the only part; the final cut sets the tail's
nextto null, which it already is. - Even split. When
n % k == 0there are no extras and every part hasn / knodes.
Common mistakes
- Giving the extra nodes to the last parts instead of the first, which breaks the "earlier is never smaller" rule.
- Cutting
cur.nextbefore saving it, which loses the rest of the list. - Returning fewer than
kparts when the list is short, instead of padding with null.
How to talk through it
- 1Clarify. Must I return exactly k parts, with nulls at the end when the list is short? Can I reuse the original nodes?
- 2Find the sizes. The length decides everything: n // k per part, plus one for the first n % k parts.
- 3Count first. A linked list hides its length, so one pass counts it.
- 4Cut in place. Walk again, recording each part's head and cutting after its last node. O(n + k) time, O(1) extra.
- 5Test out loud. Run an empty list, a list shorter than k, and one that splits evenly.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?