Split Linked List in Parts

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given the head of a singly linked list and an integer k, split the linked list into k consecutive parts as equally as possible.

The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.

Return an array of k parts, where each part is represented as an array of node values. If there are fewer nodes than k, the remaining parts should be empty arrays.

Examples

Example 1:

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

Output: [[1],[2],[3],[],[]]

Explanation: The list has 3 nodes but k=5, so the first 3 parts get one node each, and the last 2 parts are empty.

Example 2:

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

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

Explanation: 10 / 3 = 3 remainder 1. The first part gets an extra node (4 nodes), the remaining parts get 3 nodes each.

Example 3:

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

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

Explanation: 5 / 2 = 2 remainder 1. The first part gets 3 nodes and the second gets 2.

Constraints

  • The number of nodes in the list is in the range [0, 1000]
  • 0 <= Node.val <= 1000
  • 1 <= k <= 50
Source: Fast and Slow Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle