Minimum Time to Eat All Grains — LeetCode 2604 Python Solution
- Problem
- #2604
- Pattern
- Two Pointers
- Reading time
- 5 min
- Source
- leetcode.com
The problem
There are n hens and m grains on a line. You are given the initial positions of the hens and the grains in two integer arrays hens and grains of size n and m respectively.
Example
- Input
- hens = [3,6,7], grains = [2,4,7,9]
- Output
- 2
- Explanation
- One of the ways hens eat all grains in 2 seconds is described below:
Python solution
class Solution:
def minimumTime(self, hens: List[int], grains: List[int]) -> int:
def check(t):
j = 0
for x in hens:
if j == m:
return True
y = grains[j]
if y <= x:
d = x - y
if d > t:
return False
while j < m and grains[j] <= x:
j += 1
while j < m and min(d, grains[j] - x) + grains[j] - y <= t:
j += 1
else:
while j < m and grains[j] - x <= t:
j += 1
return j == m
hens.sort()
grains.sort()
m = len(grains)
r = abs(hens[0] - grains[0]) + grains[-1] - grains[0] + 1
return bisect_left(range(r), True, key=check)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 2604. Minimum Time to Eat All Grains is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2604. Minimum Time to Eat All Grains?
- LeetCode 2604. Minimum Time to Eat All Grains is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2604. Minimum Time to Eat All Grains?
- The Python solution on this page runs in O(n) (after optional sort O(n log n)).
- What is the space complexity of LeetCode 2604. Minimum Time to Eat All Grains?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2604. Minimum Time to Eat All Grains cover?
- LeetCode 2604. Minimum Time to Eat All Grains is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.
- Is LeetCode 2604. Minimum Time to Eat All Grains a premium problem?
- Yes. LeetCode 2604. Minimum Time to Eat All Grains is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.