Chocolate Distribution Problem
An easy Arrays problem included in Love Babbar 450. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 1
- Core for
- 25 roles
- Platform
- GeeksforGeeks
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=[7,3,2,4,9,12,56], m=3
- Output
- 2
Constraints
- 1 <= m <= n <= 10^5
- 0 <= packets[i] <= 10^9
How to think about it
Updated 2026-09-09When 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 packets[i + m - 1] - packets[i]. O(n log n) from the sort, O(1) extra — trying every combination is O(n choose m).
Python
def min_chocolate_diff(packets: list[int], m: int) -> int:
if m <= 1 or not packets:
return 0
sizes = sorted(packets)
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 minChocolateDiff(packets, m) {
if (m <= 1 || packets.length === 0) return 0;
const sizes = [...packets].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.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Companies that have asked it
Tags taken from the problem's own GeeksforGeeks page — not a copied list.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .