Magicsheet logo

Minimum Time to Eat All Grains

Hard
83.3%
Updated 6/1/2025

Minimum Time to Eat All Grains

What is this problem about?

The Minimum Time to Eat All Grains problem places hens and grains on a number line. Each hen can move at speed 1 and eat any grain it reaches. You want all grains to be eaten in minimum time, where each hen can eat any number of grains (in order of position). This hard Minimum Time to Eat All Grains coding problem requires sorting both arrays and binary searching on the answer with a clever two-pointer feasibility check.

Why is this asked in interviews?

Confluent asks this because it requires layering multiple techniques: sorting both arrays, binary searching on the answer (time T), and a two-pointer greedy check to verify feasibility within time T. The array, sorting, two pointers, and binary search interview pattern are all combined here, making it a comprehensive test of algorithmic integration.

Algorithmic pattern used

Binary search on time + two-pointer feasibility check. Sort hens and grains. For a given time T, use two pointers to greedily assign grains to hens: each hen eats a contiguous segment of grains. The cost for a hen at position h to eat grains from position g_left to g_right is either max(|h - g_right|, |h - g_left|) if h is inside, or the minimum of going left-first vs right-first otherwise. If all grains can be assigned, T is feasible.

Example explanation

Hens: [3, 6]. Grains: [1, 2, 4, 7].

  • T = 4: Hen 3 eats grains [1,2,4] — cost = max(3-1, 4-3) = max(2,1) = 2 ≤ 4 ✓. Hen 6 eats [7] — cost = 1 ≤ 4 ✓. Feasible!
  • T = 3: Check similarly — try with tighter time budget. Binary search finds minimum T = 4.

Common mistakes candidates make

  • Not sorting both arrays before binary searching.
  • Incorrectly computing the cost for a hen to eat a contiguous range (the "go both directions" formula is tricky).
  • Two-pointer advancing in the wrong direction.
  • Integer overflow or off-by-one in the binary search bounds.

Interview preparation tip

Multi-entity problems on a number line (hens, workers, buses) commonly require sorting both entities and binary searching on the time budget. The two-pointer check then assigns the left-most unmatched resource to the left-most unfulfilled demand. Practice computing the "cost for one entity to cover a range" carefully — the go-left-or-right-first decision is the most error-prone part. Simulate the feasibility check on paper for small cases before coding.

Similar Questions