Minimum Time to Eat All Grains - Problem
The Great Grain Hunt Challenge

Imagine a farm where n hens are scattered along a straight line, and m grains are also positioned at various points on the same line. Your mission is to help these hungry hens eat all the grains in the minimum possible time!

Here's how it works:
• Each hen can move left or right by 1 unit per second
• Multiple hens can move simultaneously and independently
• A hen eats a grain instantly when they occupy the same position
• One hen can eat multiple grains
• All grains must be consumed

The question is: What's the minimum time needed if all hens act optimally?

This is a classic assignment optimization problem where we need to smartly assign grains to hens to minimize the maximum time any hen takes.

Input & Output

example_1.py — Basic Example
$ Input: hens = [3, 6, 7], grains = [2, 4, 7, 9]
Output: 2
💡 Note: Hen at position 3 can eat grains at positions 2 and 4 (takes 2 seconds: go to 2, then to 4). Hen at position 6 can eat grain at position 7 (takes 1 second). Hen at position 7 can eat grain at position 9 (takes 2 seconds). Maximum time is 2 seconds.
example_2.py — Single Hen
$ Input: hens = [4], grains = [1, 3, 6, 8]
Output: 7
💡 Note: Single hen at position 4 must eat all grains. Optimal strategy: go to position 1 first (3 seconds), then traverse to position 8 (7 more seconds), total 7 seconds to cover range [1,8].
example_3.py — Edge Case
$ Input: hens = [0, 10], grains = [5]
Output: 5
💡 Note: Two hens at positions 0 and 10, one grain at position 5. Either hen can eat it in 5 seconds. Optimal assignment gives minimum time of 5.

Constraints

  • 1 ≤ hens.length, grains.length ≤ 2 × 104
  • -109 ≤ hens[i], grains[i] ≤ 109
  • All positions are distinct within their respective arrays
  • At least one hen and one grain are always present

Visualization

Tap to expand
Minimum Time to Eat All GrainsH1H2H3G1G2G3G4Algorithm Steps:1. Sort: Arrange hens and grains by position2. Binary Search: Search minimum feasible time3. Greedy Validation: Check if assignment possible4. Result: Each hen takes consecutive grains optimallyTime Complexity: O((n+m) × log(max_distance)) | Space: O(1)
Understanding the Visualization
1
Sort Positions
Arrange all hens and grains in order along the line
2
Binary Search
Search for the minimum possible maximum time
3
Greedy Check
For each time limit, check if feasible assignment exists
4
Optimal Solution
Find the minimum time where all grains can be collected
Key Takeaway
🎯 Key Insight: Binary search on the answer combined with greedy validation gives us the optimal O((n+m) × log(max_distance)) solution for this assignment optimization problem.
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 28
48.2K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen