Minimum Capacity Box Problem
Description
LeetCode Problem 3861.
You are given an integer array capacity, where capacity[i] represents the capacity of the i^th box, and an integer itemSize representing the size of an item.
The i^th box can store the item if capacity[i] >= itemSize.
Return an integer denoting the index of the box with the minimum capacity that can store the item. If multiple such boxes exist, return the smallest index.
If no box can store the item, return -1.
Example 1:
Input: capacity = [1,5,3,7], itemSize = 3
Output: 2
Explanation:
The box at index 2 has a capacity of 3, which is the minimum capacity that can store the item. Thus, the answer is 2.
Example 2:
Input: capacity = [3,5,4,3], itemSize = 2
Output: 0
Explanation:
The minimum capacity that can store the item is 3, and it appears at indices 0 and 3. Thus, the answer is 0.
Example 3:
Input: capacity = [4], itemSize = 5
Output: -1
Explanation:
No box has enough capacity to store the item, so the answer is -1.
Constraints:
1 <= capacity.length <= 1001 <= capacity[i] <= 1001 <= itemSize <= 100
Solution
Approach: Single Pass
Scan the boxes once, remembering the index ans of the best box so far (start at -1). A box can be used when its capacity is at least itemSize; it replaces ans only if ans is still -1 or its capacity is strictly smaller, so ties keep the smallest index.
Complexity: O(n) time and O(1) space.
class Solution:
def minimumIndex(self, capacity: List[int], itemSize: int) -> int:
ans = -1
for i, x in enumerate(capacity):
if x >= itemSize and (ans == -1 or x < capacity[ans]):
ans = i
return ans