Interview question
Chunk items for batch processing
Implements chunking for batch processing without dropping final partial batches.
TL;DR
Implements chunking for batch processing without dropping final partial batches.
Enumeration, lists, boundary cases, argument validation, and batch-processing reasoning.
Practice the problem like a real interview: restate, reason, implement, and test.
Implement ChunkItems<T>(IEnumerable<T> items, int batchSize) returning a list of batches. Each batch has at most batchSize items. The final batch may be smaller.
Input: [1, 2, 3, 4, 5], batch size 2
Output: [1, 2], [3, 4], [5]
I would validate batch size, then accumulate items into a current list. When the current list reaches batch size, I add it to the result and start a new list. After the loop, I add the current list if it has any items. I would mention that modern .NET has Enumerable.Chunk, but implementing it shows the edge cases clearly.
public static IReadOnlyList<IReadOnlyList<T>> ChunkItems<T>(
IEnumerable<T>? items,
int batchSize)
{
if (batchSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(batchSize));
}
if (items is null)
{
return Array.Empty<IReadOnlyList<T>>();
}
var result = new List<IReadOnlyList<T>>();
var current = new List<T>(batchSize);
foreach (var item in items)
{
current.Add(item);
if (current.Count == batchSize)
{
result.Add(current);
current = new List<T>(batchSize);
}
}
if (current.Count > 0)
{
result.Add(current);
}
return result;
}
The method is O(n) time and O(n) space for the returned batches. A streaming iterator version can reduce peak memory if the caller can consume batches lazily.
Enumerable.Chunk for production code.No explicit flow link is set yet, so these are nearby drills from the same path or taxonomy.