725. Split Linked List in Parts
Difficulty: Medium
Topics: Linked List
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. 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 k parts.
Example 1:
- 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.
- The last element output[4] is null, but its string representation as a ListNode is [].
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:
- The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
Constraints:
- The number of nodes in the list is in the range [0, 1000].
- 0
- 1
Hint:
- If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
Solution:
The key observation is that the number of nodes in each part should not differ by more than 1. This means:
- Calculate the length of the linked list.
- Determine the minimum size of each part (part_size = length // k).
- Distribute the extra nodes evenly across the first few parts (extra_nodes = length % k). The first extra_nodes parts should have one extra node each.
Approach
- Calculate the length: Traverse the linked list to find the total number of nodes.
-
Determine the size of each part:
- Each part should have at least length // k nodes.
- The first length % k parts should have one extra node.
-
Split the list: Use a loop to split the linked list into k parts. For each part:
- If it should have extra nodes, assign part_size + 1 nodes.
- If not, assign part_size nodes.
- Null parts: If the list is shorter than k, some parts will be empty (null).
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) { ... ... ... /** * go to ./solution.php */ } // Helper function to create a linked list from an array function createLinkedList($arr) { $head = new ListNode($arr[0]); $current = $head; for ($i = 1; $i 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:
Calculate Length: We first traverse the linked list to find its length.
-
Determine Parts:
- We calculate part_size as length // k, which gives the minimum size each part should have.
- We calculate extra_nodes as length % k, which gives the number of parts that should have one extra node.
-
Split the List: We loop through k parts and split the list:
- For each part, assign part_size + 1 nodes if it should have an extra node, otherwise just part_size.
- At the end of each part, we break the link to the rest of the list.
Handle Null Parts: If there are fewer nodes than k, the remaining parts will be null (empty).
Test Cases
- Example 1:
$head = [1,2,3]; $k = 5; Output: [[1],[2],[3],[],[]]
- Example 2:
$head = [1,2,3,4,5,6,7,8,9,10]; $k = 3; Output: [[1,2,3,4],[5,6,7],[8,9,10]]
This solution efficiently splits the linked list into k parts with a time complexity of (O(n + k)), where n is the length of the list.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
- GitHub
The above is the detailed content of . Split Linked List in Parts. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
