Split Linked List in Parts

Split a list into k roughly-equal parts (earlier parts at most one node larger).

Medium
Time O(n + k) Space O(k)
LeetCode
4 min read
linked-list

Problem#

Split the list into k consecutive parts. Earlier parts may be at most one node larger than later parts. Return the array of k heads.

Examples#

  • [1,2,3], k = 5[[1],[2],[3],[],[]]
  • [1,2,3,4,5,6,7,8,9,10], k = 3[[1,2,3,4],[5,6,7],[8,9,10]]

Constraints#

  • 0 <= length <= 100, 1 <= k <= 50.

Approach#

Count length n. Each of the first n % k parts gets ⌈n / k⌉ nodes; the rest get ⌊n / k⌋. Walk and cut.

Solution#

Split Linked List in Parts
class Solution {
public:
vector<ListNode*> splitListToParts(ListNode* head, int k) {
int n = 0;
for (ListNode* p = head; p; p = p->next) ++n;
int base = n / k, extra = n % k;
vector<ListNode*> ans(k, nullptr);
ListNode* curr = head;
for (int i = 0; i < k && curr; ++i) {
ans[i] = curr;
int size = base + (i < extra ? 1 : 0);
for (int j = 0; j < size - 1; ++j) curr = curr->next;
ListNode* nxt = curr->next;
curr->next = nullptr;
curr = nxt;
}
return ans;
}
};

Editorial#

The n % k “extra” nodes are sprinkled into the first n % k parts, one each — that’s the “earlier parts may be one node larger” rule. The cut step (curr->next = nullptr) terminates each part; we capture the next-part head before nulling.

Complexity#

  • Time: O(n + k).
  • Space: O(k) (output).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.