Optimal Crate Catalog Selection for Minimum Unused Capacity
Hard · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
A logistics warehouse must ship n individual parcels whose required volumes are given in requirements (requirements[i] is the volume of parcel i). You are offered num_container_sets candidate crate catalogs, indexed 0 through num_container_sets - 1, and must pick a single catalog to pack every parcel.
Available crate sizes are passed in containers, where each two-element row [set_index, capacity] indicates that catalog set_index provides crates of volume capacity in unlimited supply:
def choose_containers(
requirements: List[int],
num_container_sets: int,
containers: List[List[int]],
) -> int:
Packing & Scoring Rules
When evaluating a single catalog s:
- One crate per parcel: Every parcel
requirements[i]goes into its own crate chosen exclusively from catalogs. - Tightest fitting crate: Parcel
imust use the smallest crate capacity in catalogssatisfyingcapacity >= requirements[i]. An exact match (capacity == requirements[i]) leaves0unused space; otherwise the unused space for parceliiscapacity - requirements[i]. - Catalog eligibility: If catalog
shas no crate withcapacity >= requirements[i]for some parceli(including when catalogshas zero rows incontainers), catalogsis ineligible and cannot be selected. - Objective & tie-breaker: Among all eligible catalogs, return the
0-based indexswhose total unused space across allnparcels is smallest. If multiple eligible catalogs tie for the minimum total unused space, return the smallest indexs. If every catalog is ineligible, return-1.
Rows in containers appear grouped by ascending set_index, and within each catalog capacities appear in non-decreasing order (duplicate capacities may occur).
Examples
Example 1
Input:
requirements = [3, 5, 8, 8]
num_container_sets = 3
containers = [
[0, 4], [0, 7],
[1, 4], [1, 8], [1, 10],
[2, 5], [2, 9]
]
Output: 1
Walk-through:
- Catalog 0 ([4, 7]): Largest crate is 7, which cannot hold parcel volume 8 -> ineligible.
- Catalog 1 ([4, 8, 10]): 3 -> 4 (unused 1), 5 -> 8 (unused 3), 8 -> 8 (unused 0), 8 -> 8 (unused 0) -> total unused space 1 + 3 + 0 + 0 = 4.
- Catalog 2 ([5, 9]): 3 -> 5 (unused 2), 5 -> 5 (unused 0), 8 -> 9 (unused 1), 8 -> 9 (unused 1) -> total unused space 2 + 0 + 1 + 1 = 4.
- Catalogs 1 and 2 tie at 4, so the smaller index 1 wins.
Example 2
Input:
requirements = [6, 12]
num_container_sets = 2
containers = [
[0, 6], [0, 10],
[1, 4], [1, 11]
]
Output: -1
Walk-through:
- Catalog 0 tops out at 10 and catalog 1 tops out at 11. Neither can accommodate parcel volume 12, so -1 is returned.
Constraints
1 <= len(requirements) <= 10^51 <= num_container_sets <= 10^51 <= len(containers) <= 2 * 10^51 <= requirements[i] <= 10^90 <= containers[k][0] < num_container_sets1 <= containers[k][1] <= 10^9- Algorithms that scan all parcels per catalog or all rows per parcel (
O(len(requirements) * len(containers))orO(len(requirements) * num_container_sets)) will exceed the time limit at upper bounds.
Step-by-step walkthrough
Restate the problem and input layout
We have
nparcel volumes (requirements[i]) andnum_container_setscandidate crate catalogs (0throughnum_container_sets - 1). We must select one catalog to pack allnparcels:- Each parcel uses the smallest crate in the catalog with
capacity >= requirement(0unused space on an exact fit). - If any parcel exceeds every crate in a catalog (or if a catalog has zero rows), that catalog is ineligible.
- Return the eligible catalog index with the minimum total unused space (
sum(chosen_capacity - requirement)), breaking ties by the smallest index, or-1if every catalog is ineligible.
In
containers, rows have shape[set_index, capacity], with up ton <= 10^5parcels,num_container_sets <= 10^5catalogs, andT <= 2 * 10^5total container rows.- Each parcel uses the smallest crate in the catalog with
Why checking every parcel against every catalog times out
Let's check the cost of iterating over parcels for each catalog:
- Linear scan per
(catalog, parcel):O(n * T)— up to10^5 * 2 * 10^5 = 2 * 10^10checks. - Binary search a catalog's crates for each parcel: fast when there are only a few large catalogs, but what if there are
K = 10^5catalogs of2crates each (T = 2 * 10^5) andn = 10^5parcels? Visiting every(catalog, parcel)pair still executesK * n = 10^10iterations and times out!
Notice the asymmetry in the constraints:
K * ncan be10^10, whereas the total number of crate rowsTacross all catalogs combined is at most2 * 10^5! That tells us our work must loop over crate rowsT, not(catalog, parcel)pairs.- Linear scan per
Flip the perspective: count parcels per crate with binary search
Sort
requirementsonce in non-decreasing order. Now inspect one catalog's sorted capacitiesc_0 <= c_1 <= ... <= c_(m-1):- Which parcels use crate
c_0? Every parcel withrequirement <= c_0. - Which parcels use crate
c_1? Every remaining parcel withc_0 < requirement <= c_1. - In general, crate
c_jpacks every parcel in the half-open range(c_(j-1), c_j]!
sorted_requirements: [ 3, 5, 8, 8 ] (total_required = 24) ^ ^ ^ ^ Catalog 1 capacities [4, 8, 10]: c = 4: <= 4 -> [3] (1 parcel * 4 = 4) c = 8: (4, 8] -> [5, 8, 8] (3 parcels * 8 = 24) c = 10: (all 4 parcels already packed -> stop!) total_capacity_used = 28 unused = 28 - 24 = 4Notice two clean shortcuts in that diagram:
- Calling Python's
bisect_right(sorted_requirements, capacity)finds how many parcels satisfyrequirement <= capacityinO(log n)time. Subtractingorders_packed_so_fargives the exact count of parcels landing incapacity! - Instead of summing
capacity - requirementparcel by parcel, we sumnewly_packed_orders * capacityacross the crates to gettotal_capacity_used, and subtracttotal_required = sum(requirements)once at the end!
- Which parcels use crate
Group crate rows by catalog index
First we bucket the
[set_index, capacity]rows intocapacities_by_set, leaving an empty list[]for any catalog index that has no rows. Sorting each bucket isO(T)on already-sorted input (Python's Timsort runs in linear time on sorted runs) and protects us if capacities ever arrive unsorted:from bisect import bisect_right def group_capacities( num_container_sets: int, containers: List[List[int]] ) -> List[List[int]]: """Group [set_index, capacity] rows into capacities_by_set[s] sorted non-decreasing.""" # capacities_by_set[s]: sorted capacities for set s, e.g. [[4, 7], [4, 8, 10], [5, 9]]. capacities_by_set: List[List[int]] = [] for _ in range(num_container_sets): capacities_by_set.append([]) for set_index, capacity in containers: capacities_by_set[set_index].append(capacity) # Input rows are already non-decreasing per set; sorting again is an O(T) safety net # (Timsort is linear on sorted runs) that also handles unsorted rows automatically. for set_capacities in capacities_by_set: set_capacities.sort() return capacities_by_setCompute one catalog's unused space (and why bisect_right matters)
Before looping over a catalog's capacities, how do we check whether it can pack every parcel? Both
sorted_requirementsandset_capacitiesare sorted, so every parcel fits if and only if the catalog is non-empty and its largest crate fits the largest parcel:set_capacities[-1] >= sorted_requirements[-1]. If not, we returnNoneso the caller never confuses an ineligible catalog with0unused space.Why
bisect_rightinstead ofbisect_left? Supposesorted_requirements = [3, 5, 8, 8]andcapacity = 8: -bisect_rightplaces the split after both8s (index4), packing both8s into crate8with0unused space. -bisect_leftwould stop before the8s (index2), mistakenly pushing exact-fit8s into crate10!What if a catalog lists duplicate capacities like
[4, 4, 8]? The second4producesorders_fitting_upto_here == orders_packed_so_far, adding0 * 4 = 0, so duplicates work automatically.def compute_set_waste( sorted_requirements: List[int], total_required: int, set_capacities: List[int] ) -> Optional[int]: """Return total waste for one sorted container set, or None if any order cannot fit.""" # Validity check: the set must be non-empty and its largest container must fit the largest order. if len(set_capacities) == 0 or set_capacities[-1] < sorted_requirements[-1]: return None num_orders = len(sorted_requirements) total_capacity_used = 0 # orders_packed_so_far counts orders with requirement <= the previous container capacity. orders_packed_so_far = 0 for capacity in set_capacities: # bisect_right returns the count of orders with requirement <= capacity (exact fits included). orders_fitting_upto_here = bisect_right(sorted_requirements, capacity) newly_packed_orders = orders_fitting_upto_here - orders_packed_so_far total_capacity_used += newly_packed_orders * capacity orders_packed_so_far = orders_fitting_upto_here if orders_packed_so_far == num_orders: # Every order has already been assigned to its smallest fitting container. break # sum(chosen_capacity_i - requirement_i) == sum(chosen_capacity_i) - sum(requirement_i). return total_capacity_used - total_requiredPick the winning catalog and trace Example 1
Finally, we scan
set_indexfrom0tonum_container_sets - 1and updatebest_set_indexonly whenwaste < best_waste(strict<), so any tie keeps the smaller index:Example 1 trace: sorted_requirements = [3, 5, 8, 8], total_required = 24 Catalog 0 [4, 7]: max 7 < 8 (ineligible -> None, skipped) Catalog 1 [4, 8, 10]: max 10 >= 8 (eligible) cap 4 -> bisect_right=1 -> 1 new parcel -> +4 cap 8 -> bisect_right=4 -> 3 new parcels -> +24 (all 4 packed, break early!) => used 28, unused = 28 - 24 = 4 (best = 1) Catalog 2 [5, 9]: max 9 >= 8 (eligible) cap 5 -> bisect_right=2 -> 2 new parcels -> +10 cap 9 -> bisect_right=4 -> 2 new parcels -> +18 => used 28, unused = 28 - 24 = 4 (tie: keep 1) Returns: 1Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from bisect import bisect_right def group_capacities( num_container_sets: int, containers: List[List[int]] ) -> List[List[int]]: """Group [set_index, capacity] rows into capacities_by_set[s] sorted non-decreasing.""" # capacities_by_set[s]: sorted capacities for set s, e.g. [[4, 7], [4, 8, 10], [5, 9]]. capacities_by_set: List[List[int]] = [] for _ in range(num_container_sets): capacities_by_set.append([]) for set_index, capacity in containers: capacities_by_set[set_index].append(capacity) # Input rows are already non-decreasing per set; sorting again is an O(T) safety net # (Timsort is linear on sorted runs) that also handles unsorted rows automatically. for set_capacities in capacities_by_set: set_capacities.sort() return capacities_by_set def compute_set_waste( sorted_requirements: List[int], total_required: int, set_capacities: List[int] ) -> Optional[int]: """Return total waste for one sorted container set, or None if any order cannot fit.""" # Validity check: the set must be non-empty and its largest container must fit the largest order. if len(set_capacities) == 0 or set_capacities[-1] < sorted_requirements[-1]: return None num_orders = len(sorted_requirements) total_capacity_used = 0 # orders_packed_so_far counts orders with requirement <= the previous container capacity. orders_packed_so_far = 0 for capacity in set_capacities: # bisect_right returns the count of orders with requirement <= capacity (exact fits included). orders_fitting_upto_here = bisect_right(sorted_requirements, capacity) newly_packed_orders = orders_fitting_upto_here - orders_packed_so_far total_capacity_used += newly_packed_orders * capacity orders_packed_so_far = orders_fitting_upto_here if orders_packed_so_far == num_orders: # Every order has already been assigned to its smallest fitting container. break # sum(chosen_capacity_i - requirement_i) == sum(chosen_capacity_i) - sum(requirement_i). return total_capacity_used - total_required def choose_containers( requirements: List[int], num_container_sets: int, containers: List[List[int]] ) -> int: # Phase 1: Sort requirements once so every container row can binary-search it in O(log n). sorted_requirements = sorted(requirements) total_required = sum(requirements) capacities_by_set = group_capacities(num_container_sets, containers) # Phase 2: Evaluate each set in index order and keep the minimum waste. best_set_index = -1 best_waste = 0 for set_index in range(num_container_sets): waste = compute_set_waste( sorted_requirements, total_required, capacities_by_set[set_index] ) if waste is None: continue # Use strict `<` so ties keep the earlier (smaller) set_index. if best_set_index == -1 or waste < best_waste: best_set_index = set_index best_waste = waste return best_set_index✅ Submit now — all tests should pass.
Intuition & how it works
Imagine lining up 100,000 outgoing parcels on a long sorting conveyor belt arranged from smallest volume to largest volume, and comparing 100,000 vendor crate catalogs where an average catalog only offers 2 crate sizes (say 5L and 10L). If you pick up every parcel and test it against every catalog, you perform 100,000 * 100,000 = 10 billion checks! Instead, for a [5L, 10L] catalog, simply drop two dividers onto the sorted conveyor belt — one right after the last parcel <= 5L, and one right after the last parcel <= 10L. Every parcel before the first divider uses 5L crates, and every parcel between the two dividers uses 10L crates!
Why do both obvious approaches time out? Scanning a catalog's crates linearly for each parcel takes O(n * T) (~2 * 10^10 steps). Even using binary search (repeatedly halving a sorted array to find a boundary in O(log m) steps) to look up a crate for each parcel still visits every (catalog, parcel) pair, which takes K * n = 10^5 * 10^5 = 10^10 iterations when 10^5 catalogs have 2 crates each. Flipping the search so each crate row uses bisect_right (an upper-bound binary search returning the index right after all elements <= x) on the sorted requirements array runs at most T <= 2 * 10^5 binary searches in total!
Let's trace Example 1 (requirements = [3, 5, 8, 8], total_required = 24) across the three catalogs:
sorted_requirements: [3, 5, 8, 8]
Catalog 0 [4, 7]: max 7 < 8 (ineligible -> skipped)
Catalog 1 [4, 8, 10]: max 10 >= 8 (eligible)
cap 4: <= 4 -> 1 parcel [3] (used += 1 * 4 = 4)
cap 8: (4, 8] -> 3 parcels [5, 8, 8] (used += 3 * 8 = 24) -> unused = 28 - 24 = 4
Catalog 2 [5, 9]: max 9 >= 8 (eligible)
cap 5: <= 5 -> 2 parcels [3, 5] (used += 2 * 5 = 10)
cap 9: (5, 9] -> 2 parcels [8, 8] (used += 2 * 9 = 18) -> unused = 28 - 24 = 4 (tie -> keep 1)
Answer: Catalog 1
Complexity
Let n be len(requirements), K be num_container_sets, and T be len(containers) (n, K <= 10^5, T <= 2 * 10^5).
- Time:
O(n log n + T log n + K)(orO((n + T) log n + T log T + K)if rows within a catalog are unsorted). Sortingrequirementsonce takesO(n log n)time, groupingTrows intoKbuckets takesO(K + T)time (plusO(T)for Python's Timsort on already-sorted buckets, orO(T log T)worst-case), andcompute_set_wasteperforms at most oneO(log n)bisect_rightcall per crate row (Trows total) plus oneO(K)pass to select the winner. At the maximum bounds that is roughly3.5million operations, finishing well under a tenth of a second. - Space:
O(n + K + T).sorted_requirementsholdsnintegers, andcapacities_by_setholdsKlist headers containingTcapacities in total.
Edge cases
- No eligible catalog: Every catalog's largest capacity is strictly smaller than
sorted_requirements[-1], sobest_set_indexremains-1. - Exact fit on the largest parcel (
set_capacities[-1] == sorted_requirements[-1]): Eligible because the rule requirescapacity >= requirement, so only<disqualifies a catalog. - Catalog index with zero rows:
len(set_capacities) == 0returnsNoneimmediately rather than raisingIndexErroror falsely reporting0unused space. - Exact fits and
0total unused space:bisect_rightincludes elements equal tocapacity, assigning exact matches0slack; returningNone(not0or-1) for ineligible catalogs keeps0distinct from "ineligible". - Ties on minimum unused space: Updating
best_set_indexonly on strict<(waste < best_waste) guarantees the smallest index wins every tie, even when ineligible catalogs appear before or between tied catalogs (as in Example 1). - Duplicate capacities or duplicate parcel volumes: A repeated capacity in
[4, 4, 8]getsnewly_packed_orders = 0on its second occurrence, and repeated volumes in[3, 5, 8, 8]are counted together inO(log n)time. - 64-bit total unused space: Up to
10^5parcels of volume1packed into10^9-capacity crates produce~10^14unused units, exceeding 32-bit signedint(~2.1 * 10^9); Pythonintis arbitrary-precision, while C++/Java requirelong long/long.
Common mistakes
- Binary-searching crates per parcel (
O(K * n log m)): Times out wheneverKandnare both10^5(for instance,10^5catalogs of2crates each). - Using
bisect_leftinstead ofbisect_right:bisect_leftcounts only parcels strictly< capacity, which pushes exact-fit parcels (requirement == capacity) into the next larger crate (or leaves parcels equal toset_capacities[-1]completely unpacked, producing a negative or wrong score!). - Skipping the eligibility check (
set_capacities[-1] < sorted_requirements[-1]): Without checking the largest parcel first,total_capacity_usedleaves oversized parcels unpacked (0 * capacity) and makes ineligible catalogs look artificially cheap or even negative! - Sorting
requirementsinside thefor set_indexloop: Turns oneO(n log n)sort intoO(K * n log n)(~1.7 * 10^11operations). - Breaking ties with
<=instead of<: Overwrites the earlier tied index and returns the largest tied catalog index instead of the smallest.
Alternative approaches
- Per-group unused space via prefix sums (
O((n + T) log n + K)): Build a prefix sum array (running totals ofsorted_requirementsso any slice sum isprefix[r] - prefix[l]inO(1)time) and accumulatenewly_packed_orders * capacity - (prefix[upto] - prefix[prev])per crate. Algebraically those slice sums telescope tototal_required, so subtractingtotal_requiredonce at the end gets the exact same answer without allocating the prefix array.
Follow-up questions
- How would the implementation change if catalogs arrived as a nested list of unsorted capacity arrays that might contain duplicate sizes? Skip the
[set_index, capacity]grouping step and simply passsorted(catalogs[s])directly intocompute_set_wastefor eachsinrange(len(catalogs)). Duplicate capacities insidesorted(catalogs[s])do not even need explicit deduplication because the repeated call tobisect_rightyieldsnewly_packed_orders == 0. - Suppose each crate size has a monetary price
[set_index, capacity, cost]and you want the lowest total bill rather than the least unused volume—how does your solution adapt? If parcels must still use the smallest fitting crate, keep capacities sorted ascending and accumulatenewly_packed_orders * cost(without subtractingtotal_required). If you may choose any crate withcapacity >= requirementto minimize dollar spend, a larger crate might be cheaper than a smaller one, so first compute suffix-minimum costscheapest_from_here[j] = min(cost[j:])from right to left within each catalog and accumulatenewly_packed_orders * cheapest_from_here[j]. - If the crate catalogs remain static while thousands of independent order batches arrive throughout the day, how would you preprocess and query them? Preprocess
capacities_by_setonce inO(T log T + K)time and keep the sorted per-catalog lists in memory; each incoming batch ofnparcels then sorts its ownrequirementsand evaluates catalogs. Ifnis tiny on some batches (n << T / K) while large on others, dispatch dynamically per catalog of sizem: binary-search crates per parcel (O(n log m)) whenn < m, and binary-search parcels per crate (O(m log n)) whenm <= n!
Follow-up questions
- How would the implementation change if catalogs arrived as a nested list of unsorted capacity arrays that might contain duplicate sizes?
- Suppose each crate size has a monetary price `[set_index, capacity, cost]` and you want the lowest total bill rather than the least unused volume—how does your solution adapt?
- If the crate catalogs remain static while thousands of independent order batches arrive throughout the day, how would you preprocess and query them?
Similar questions
- K-th Subordinate in Hierarchy Broadcast Order
- Pivoting an Analytical Project Under Shifting Priorities
- Single-Issue Pipeline Timing and Roofline Bottleneck Analysis
- Strategic Budget Allocation Across Voting Districts
- Worst-Case Operation Bounds and Multithreading Limits
- Signed Bit Shifts, Cache Eviction, and Graph Degrees
More Imc interview questions
- Probability Squared Maximum Beats Minimum Hard
- Strategic Budget Allocation Across Voting Districts Hard
- Single-Issue Pipeline Timing and Roofline Bottleneck Analysis Easy Pro
- K-th Subordinate in Hierarchy Broadcast Order Medium Pro
- Pivoting an Analytical Project Under Shifting Priorities Medium Pro
- Worst-Case Operation Bounds and Multithreading Limits Medium Pro
- Signed Bit Shifts, Cache Eviction, and Graph Degrees Medium Pro
- Absorption Probability and Fair Stopping Time Medium Pro
- In-Memory Hotel Reservation Engine Medium Pro
- OLS Gauss-Markov Theory and Transformer Self-Attention Medium Pro