725. Split Linked List in Parts #503
-
Topics: Given the The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. The parts should be in the 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 the Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The key observation is that the number of nodes in each part should not differ by more than 1. This means:
Approach
Let's implement this solution in PHP: 725. Split Linked List in Parts <?php
// Definition for singly-linked list.
class ListNode {
public $val = 0;
public $next = null;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
/**
* @param ListNode $head
* @param Integer $k
* @return ListNode[]
*/
function splitListToParts($head, $k) {
$length = 0;
$current = $head;
// Calculate the total length of the linked list
while ($current !== null) {
$length++;
$current = $current->next;
}
// Determine the size of each part
$part_size = intval($length / $k);
$extra_nodes = $length % $k;
// Prepare result array
$result = array_fill(0, $k, null);
$current = $head;
for ($i = 0; $i < $k && $current !== null; $i++) {
$result[$i] = $current; // Start of the ith part
$current_size = $part_size + ($extra_nodes > 0 ? 1 : 0);
$extra_nodes--;
// Move to the end of the current part
for ($j = 1; $j < $current_size; $j++) {
$current = $current->next;
}
// Break the current part from the rest of the list
$next = $current->next;
$current->next = null;
$current = $next;
}
return $result;
}
// Helper function to create a linked list from an array
function createLinkedList($arr) {
$head = new ListNode($arr[0]);
$current = $head;
for ($i = 1; $i < count($arr); $i++) {
$current->next = new ListNode($arr[$i]);
$current = $current->next;
}
return $head;
}
// Helper function to print a linked list
function printList($head) {
$result = [];
while ($head !== null) {
$result[] = $head->val;
$head = $head->next;
}
return $result;
}
// Test case 1
$head = createLinkedList([1, 2, 3]);
$k = 5;
$result = splitListToParts($head, $k);
foreach ($result as $part) {
print_r(printList($part));
}
// Test case 2
$head = createLinkedList([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$k = 3;
$result = splitListToParts($head, $k);
foreach ($result as $part) {
print_r(printList($part));
}
?> Explanation:
Test Cases
This solution efficiently splits the linked list into |
Beta Was this translation helpful? Give feedback.
The key observation is that the number of nodes in each part should not differ by more than 1. This means:
part_size = length // k
).extra_nodes = length % k
). The firstextra_nodes
parts should have one extra node each.Approach
length // k
nodes.length % k
parts should have one extra node.k
parts. For each part: