Chocolate Distribution Problem
An easy Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Arrays
- Sheets
- 1
- Core for
- 26 roles
The problem
Given an array of chocolate packet sizes and a number of students, distribute packets so that each student gets one packet and the difference between the maximum and minimum packets received is minimized.
Example 1
- Input
- packets=[1,4,7,2,9], m=3
- Output
- 3
Example 2
- Input
- packets=[8,5,11,2,14,9,33], m=3
- Output
- 3
Constraints
- 1 <= m <= n <= 10^5
- 0 <= packets[i] <= 10^9
How to think about it
Updated 2026-09-29When numbers are sorted, any subset with minimal spread between its extreme values must occupy contiguous positions. Scrambled choices can only introduce wider gaps, so sorting converts a combinatorial search over combinations into a simple sliding window of fixed width.
Approaches, worst first
Exhaustive combinations
time O(n choose m) · space O(m)
Generate every subset of m packets from the n available, compute max minus min for each group, and track the global minimum. Computationally explodes as n grows, making it completely infeasible for practical input bounds.
Sort and slide fixed windowWrite this one
time O(n log n) · space O(1)
Sort the packets ascending, then slide a window of length m from index 0 up to n - m. At each step, the boundary difference is packets[i + m - 1] - packets[i], and the smallest evaluated gap wins.
Where people lose marks · 3
- Running the sliding window loop past index `n - m`, which triggers an out-of-bounds read at `i + m - 1`.
- Assuming m = 1 requires a difference calculation when the spread for one student is always 0.
- Integer overflow during difference evaluation if packet counts are represented as 32-bit signed integers near 10^9 in languages without arbitrary precision.
Full solution
Sort, then slide a fixed window of m over the sorted packets: the tightest group of m values must be contiguous once sorted, so the answer is the smallest arr[i + m - 1] - arr[i]. O(n log n) from the sort, O(1) extra - trying every combination is O(n choose m).
Python
def find_min_diff(arr: list[int], m: int) -> int:
if m <= 1 or not arr:
return 0
sizes = sorted(arr)
best = sizes[m - 1] - sizes[0]
# windows start at 0..n-m; the last valid right edge is index n-1
for i in range(1, len(sizes) - m + 1):
best = min(best, sizes[i + m - 1] - sizes[i])
return best
JavaScript
function findMinDiff(arr, m) {
if (m <= 1 || arr.length === 0) return 0;
const sizes = [...arr].sort((a, b) => a - b);
let best = sizes[m - 1] - sizes[0];
// windows start at 0..n-m; the last valid right edge is index n-1
for (let i = 1; i <= sizes.length - m; i++) {
best = Math.min(best, sizes[i + m - 1] - sizes[i]);
}
return best;
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
More Arrays problems
Target Roles
Core requirement for 26 roles:
Asked at
Track in your role's order
Pick your target role and all 370 problems resequence to what that interview actually asks.
Start freeProblem set and role mapping as of .