Split Linked List in Parts

Given the head of a singly linked list and an integer k, split the list into k consecutive parts. The lengths of the parts should be as equal as possible: no two parts may differ in size by more than one, which may leave some parts empty (null). Parts appear in input order, and earlier parts are always at least as long as later ones. Return an array of the k parts.

30:00

Split Linked List in Parts
medium
Free written solution
Topics
Companies

Given the head of a singly linked list and an integer k, split the list into k consecutive parts. The lengths of the parts should be as equal as possible: no two parts may differ in size by more than one, which may leave some parts empty (null). Parts appear in input order, and earlier parts are always at least as long as later ones. Return an array of the k parts.

Example 1:
Input: {"head":[1,2,3],"k":5}
Output: [[1],[2],[3],[],[]]
Constraints:
  • The number of nodes in the list is in the range [0,1000][0, 1000].

  • 0≤Node.val≤10000 \leq \text{Node.val} \leq 1000

  • 1≤k≤501 \leq k \leq 50

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"head":[1,2,3],"k":5}

Count node 1: n = 1.

n1
k5
size = n // k?
extra = n % k?

Input list (colored by the part it lands in)

1

n=1

→
2

→
3

→ null

parts[] (k = 5 slots)

parts[0]

...

parts[1]

...

parts[2]

...

parts[3]

...

parts[4]

...

Variables
VariableValue
n1
k5
size-
extra-
i-
currnull
DepthFunction Call
Stack empty
0/15