Skip to content

Commit 3b92a1b

Browse files
committedMar 12, 2025
Add solution #725
1 parent a1ed359 commit 3b92a1b

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,7 @@
549549
721|[Accounts Merge](./0721-accounts-merge.js)|Medium|
550550
722|[Remove Comments](./0722-remove-comments.js)|Medium|
551551
724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy|
552+
725|[Split Linked List in Parts](./0725-split-linked-list-in-parts.js)|Medium|
552553
733|[Flood Fill](./0733-flood-fill.js)|Easy|
553554
735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium|
554555
739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium|
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* 725. Split Linked List in Parts
3+
* https://leetcode.com/problems/split-linked-list-in-parts/
4+
* Difficulty: Medium
5+
*
6+
* Given the head of a singly linked list and an integer k, split the linked list into k
7+
* consecutive linked list parts.
8+
*
9+
* The length of each part should be as equal as possible: no two parts should have a size
10+
* differing by more than one. This may lead to some parts being null.
11+
*
12+
* The parts should be in the order of occurrence in the input list, and parts occurring
13+
* earlier should always have a size greater than or equal to parts occurring later.
14+
*
15+
* Return an array of the k parts.
16+
*/
17+
18+
/**
19+
* Definition for singly-linked list.
20+
* function ListNode(val, next) {
21+
* this.val = (val===undefined ? 0 : val)
22+
* this.next = (next===undefined ? null : next)
23+
* }
24+
*/
25+
/**
26+
* @param {ListNode} head
27+
* @param {number} k
28+
* @return {ListNode[]}
29+
*/
30+
var splitListToParts = function(head, k) {
31+
let count = 0;
32+
let current = head;
33+
34+
while (current) {
35+
count++;
36+
current = current.next;
37+
}
38+
39+
const base = Math.floor(count / k);
40+
const extra = count % k;
41+
const result = new Array(k).fill(null);
42+
43+
current = head;
44+
for (let i = 0; i < k && current; i++) {
45+
result[i] = current;
46+
const partSize = base + (i < extra ? 1 : 0);
47+
for (let j = 1; j < partSize; j++) {
48+
current = current.next;
49+
}
50+
const next = current.next;
51+
current.next = null;
52+
current = next;
53+
}
54+
55+
return result;
56+
};

0 commit comments

Comments
 (0)
Please sign in to comment.