Split Linked List in Parts - Problem

Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.

The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.

The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.

Return an array of the k parts.

Input & Output

Example 1 — Basic Split
$ Input: head = [1,2,3], k = 5
Output: [[1],[2],[3],[],[]]
💡 Note: Length 3 split into 5 parts: first 3 parts get 1 node each, last 2 parts are empty
Example 2 — Even Distribution
$ 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]]
💡 Note: Length 10 split into 3 parts: base size 3, remainder 1, so first part gets 4 nodes
Example 3 — Single Node
$ Input: head = [1], k = 1
Output: [[1]]
💡 Note: Single node in single part

Constraints

  • The number of nodes in the list is in the range [0, 1000]
  • 1 ≤ k ≤ 50
  • 0 ≤ Node.val ≤ 1000

Visualization

Tap to expand
Split Linked List in PartsInput: [1,2,3,4,5], k = 312345Length = 5, k = 3 → base = 1, remainder = 2Part 1[1, 2]Part 2[3, 4]Part 3[5]Output: [[1,2], [3,4], [5]]First 2 parts get extra node (size 2), last part gets base size (1)
Understanding the Visualization
1
Input
Linked list [1,2,3,4,5] and k=3
2
Calculate
Length=5, base=1, remainder=2 → sizes [2,2,1]
3
Split
Break connections to create [[1,2], [3,4], [5]]
Key Takeaway
🎯 Key Insight: First (remainder) parts get one extra node when length doesn't divide evenly
Asked in
Facebook 15 Microsoft 12 Amazon 8
28.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen