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 Parts INPUT Linked List (head): 1 2 3 null Input Values: head = [1, 2, 3] k = 5 List Properties: Length (n) = 3 Parts to split (k) = 5 Base size: 3 / 5 = 0 Extra nodes: 3 % 5 = 3 ALGORITHM STEPS 1 Calculate Sizes base = n/k, extra = n%k 2 Distribute Extra First 3 parts get +1 node 3 Split List Cut after each part size 4 Fill Remaining Parts 4-5 are empty (null) Part Size Distribution: Part 0: 0 + 1 = 1 node [1] Part 1: 0 + 1 = 1 node [2] Part 2: 0 + 1 = 1 node [3] Part 3: 0 + 0 = 0 nodes [] Part 4: 0 + 0 = 0 nodes [] FINAL RESULT 5 Parts Created: Part 0: 1 null Part 1: 2 null Part 2: 3 null Part 3: null (empty) Part 4: null (empty) OUTPUT: [[1],[2],[3],[],[]] OK - 5 parts created Key Insight: When n < k, each node becomes its own part, and remaining parts are null/empty. Formula: First (n % k) parts get (n/k + 1) nodes, rest get (n/k) nodes. Single pass O(n) solution! TutorialsPoint - Split Linked List in Parts | Single Pass Split Approach
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