Split Linked List in Parts

Medium · Linked Lists · Linked List

Problem

Given the head of a singly linked list and an integer k, cut the list into exactly k consecutive parts and return them as a list of k heads.

When k is larger than the number of nodes, the trailing parts are empty (None).

from_list([1,2,3]) builds a list and to_list(head) reads one back; the tests compare to_list of every part.

Examples

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

Seven nodes give sizes 3, 2 and 2, with the larger part first.

Input: head = [1,2], k = 4
Output: [[1],[2],[],[]]

Only two nodes exist, so the last two parts are empty.

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

Two parts of three.

Constraints

Approaches

Follow-up

Two passes, the first only to count, keep the extra space at O(1) beyond the output. The use cases put the longer parts last and cut by a fixed part size instead of a fixed number of parts.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…