725. Split Linked List in Parts
MediumView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
Divide linked list of length n into k parts as evenly as possible. First (n%k) parts get one extra node.
Algorithm
- 1Count length n. base = n/k, extra = n%k.
- 2For each part i: size = base + (i < extra ? 1 : 0). Extract that many nodes, break the link.
Common Pitfalls
- •Store the next node before breaking the link. Handle n < k (some parts will be null).
725.cs
C#
// Approach: Count total length, divide into k parts; first (length % k) parts get one extra node.
// Time: O(n) Space: O(1)
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}
public class Solution
{
public ListNode[] SplitListToParts(ListNode root, int k)
{
ListNode[] ans = new ListNode[k];
int length = GetLength(root);
int subLength = length / k;
int remainder = length % k;
ListNode prev = null;
ListNode head = root;
for (int i = 0; i < k; ++i, --remainder)
{
ans[i] = head;
for (int j = 0; j < subLength + (remainder > 0 ? 1 : 0); ++j)
{
prev = head;
head = head.next;
}
if (prev != null)
prev.next = null;
}
return ans;
}
private int GetLength(ListNode root)
{
int length = 0;
for (ListNode curr = root; curr != null; curr = curr.next)
++length;
return length;
}
}Advertisement
Was this solution helpful?