LeetCode #725: Split Linked List in Parts, Count Then Cut
Brute To Best
0:00 / 0:00
LeetCode #725: Split Linked List in Parts, Count Then Cut
19 просмотров · 2 недели назад
Brute To Best
101 подписчик
19 просмотров · 2 недели назад
Brute to Best: every LeetCode problem, from the naive solution to the optimal one.
In this video:
The problem: split a linked list into k consecutive parts. The part sizes can differ by at most 1, and earlier parts are the larger ones. Parts that get no nodes are null.
Brute force: copy the nodes into an array, slice it, and rebuild k lists. It works but uses O(N) extra memory.
The key insight: count the length n first. Every part gets n ÷ k nodes, and the first n % k parts get one extra.
Walk the list again. For each part, move forward size − 1 steps, then cut the next pointer and start the next part.
If k is greater than n, the remaining parts are null.
Dry run on 1 to 10 with k = 3: 10 ÷ 3 = 3 with remainder 1, so the parts are 1–4, 5–7 and 8–10.
Complexity: O(N + K) time and O(K) space for the output.
Problem: https://leetcode.com/problems/split-l...
Related: Rotate List (61), Odd Even Linked List (328), Reverse Nodes in k-Group (25)
Full Brute to Best playlist on the channel.
Subscribe for a new LeetCode problem, solved from brute force to the best solution, every day.
Hashtags
#leetcode #leetcode725 #splitlinkedlistinparts #linkedlist #pointers #math #simulation #medium #coding #codinginterview #dsa #python #faang #leetcodedaily #brutetobest