Split Linked List in Parts

Medium Topics Company Tags

Split the singly linked list into exactly k consecutive parts, preserving node order. Make their lengths differ by at most 1, with longer parts before shorter parts. Return an array containing the head of each part. Some parts can be empty. In examples and test inputs, arrays show list values from head to tail; each [] in the output represents an empty part.

Example 1:

Split Linked List in Parts, example 1: illustration of the example

Input: head = [1,2,3,4,5,6,7]
k = 3

Output: [[1,2,3],[4,5],[6,7]]

Explanation: Seven nodes split into three parts have lengths 3, 2, and 2. The extra node goes in the first part, and all nodes stay in their original order.

Example 2:

Split Linked List in Parts, example 2: illustration of the example

Input: head = [8,9]
k = 4

Output: [[8],[9],[],[]]

Explanation: There are more parts than nodes. Put one node in each of the first two parts and leave the final two parts empty.

Example 3:

Split Linked List in Parts, example 3: illustration of the example

Input: head = []
k = 2

Output: [[],[]]

Explanation: The input list is empty, but the result must still contain exactly two parts. Both parts are empty.

Constraints:

  • The list contains between 0 and 1000 nodes.
  • 0 <= Node.val <= 1000
  • 1 <= k <= 50


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.