LeetCode: Split Linked List in Parts Solution
Naming is hardApproach
Let
n
be the size of the listEach part of
k
parts will have n / k
elements plus extra 1 element if the part index is less than n % k
Naming explanation
1dividend = divisor * quotient + remainder23eg. 10 = 3 * 3 + 1
Implementation
1var splitListToParts = function (head, k) {2 let n = 03 let iter = head4 let res = Array(k).fill(null)56 for (; iter; iter = iter.next, n++) {}78 // naming explanation:9 // dividend = divisor * quotient + remainder10 let quotient = Math.floor(n / k)11 let remainder = n % k1213 iter = head1415 for (let part = 0; part < k && iter; part++) {16 let partSize = quotient + (part < remainder ? 1 : 0)1718 // init first element19 let prev = (res[part] = new ListNode(iter.val))20 iter = iter.next21 partSize--2223 // add the rest24 while (partSize-- && iter) {25 prev.next = new ListNode(iter.val)26 prev = prev.next27 iter = iter.next28 }29 }3031 return res32}
References
Similar problems
Comments
Loading comments...
Tags
leetcode
linked list
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.