Skip to contentKEEP THE CRAFTTHE SANCTUARY

Split Linked List in Parts

Cut a linked list into k consecutive parts whose sizes differ by at most one.

The problem

Implement Solution.splitListToParts(head, k). Split the linked list into k consecutive parts and return a Python list of the k part heads. The sizes of any two parts differ by at most one, and earlier parts are never smaller than later ones. The parts keep the original order, so joining them gives back the input, and each part must end with None. If there are fewer nodes than k, some parts are empty and are returned as None. For example, 1 -> 2 -> ... -> 10 with k = 3 gives [1 -> 2 -> 3 -> 4, 5 -> 6 -> 7, 8 -> 9 -> 10]. The list has at most 1,000 nodes and k is between 1 and 50.

Starter code

class Solution:
    def splitListToParts(self, head, k):
        pass

Public examples

  1. head = [1, 2, 3], k = 5gives[[1], [2], [3], None, None]
  2. head = [1, 2, 3, 4], k = 2gives[[1, 2], [3, 4]]
  3. head = [], k = 3gives[None, None, None]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.