Split Linked List in Parts — LeetCode 725 Python Solution

MediumLinked List
Problem
#725
Reading time
5 min

The 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.

Example

Input
head = [1,2,3], k = 5
Output
[[1],[2],[3],[],[]]
Explanation
The first element output[0] has output[0].val = 1, output[0].next = null.

Python solution

Python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def splitListToParts(
        self, head: Optional[ListNode], k: int
    ) -> List[Optional[ListNode]]:
        n = 0
        cur = head
        while cur:
            n += 1
            cur = cur.next
        cnt, mod = divmod(n, k)
        ans = [None] * k
        cur = head
        for i in range(k):
            if cur is None:
                break
            ans[i] = cur
            m = cnt + int(i < mod)
            for _ in range(1, m):
                cur = cur.next
            nxt = cur.next
            cur.next = None
            cur = nxt
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(k) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 725. Split Linked List in Parts is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 725. Split Linked List in Parts?
LeetCode 725. Split Linked List in Parts is rated Medium on LeetCode.
What is the time complexity of LeetCode 725. Split Linked List in Parts?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 725. Split Linked List in Parts?
The Python solution on this page uses O(k) auxiliary space.
What topics does LeetCode 725. Split Linked List in Parts cover?
LeetCode 725. Split Linked List in Parts is tagged Linked List on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview