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:

  1. One crate per parcel: Every parcel requirements[i] goes into its own crate chosen exclusively from catalog s.
  2. Tightest fitting crate: Parcel i must use the smallest crate capacity in catalog s satisfying capacity >= requirements[i]. An exact match (capacity == requirements[i]) leaves 0 unused space; otherwise the unused space for parcel i is capacity - requirements[i].
  3. Catalog eligibility: If catalog s has no crate with capacity >= requirements[i] for some parcel i (including when catalog s has zero rows in containers), catalog s is ineligible and cannot be selected.
  4. Objective & tie-breaker: Among all eligible catalogs, return the 0-based index s whose total unused space across all n parcels is smallest. If multiple eligible catalogs tie for the minimum total unused space, return the smallest index s. 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^5
  • 1 <= num_container_sets <= 10^5
  • 1 <= len(containers) <= 2 * 10^5
  • 1 <= requirements[i] <= 10^9
  • 0 <= containers[k][0] < num_container_sets
  • 1 <= containers[k][1] <= 10^9
  • Algorithms that scan all parcels per catalog or all rows per parcel (O(len(requirements) * len(containers)) or O(len(requirements) * num_container_sets)) will exceed the time limit at upper bounds.

Step-by-step walkthrough

  1. Restate the problem and input layout

    We have n parcel volumes (requirements[i]) and num_container_sets candidate crate catalogs (0 through num_container_sets - 1). We must select one catalog to pack all n parcels:

    • Each parcel uses the smallest crate in the catalog with capacity >= requirement (0 unused 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 -1 if every catalog is ineligible.

    In containers, rows have shape [set_index, capacity], with up to n <= 10^5 parcels, num_container_sets <= 10^5 catalogs, and T <= 2 * 10^5 total container rows.

  2. Why checking every parcel against every catalog times out

    Let's check the cost of iterating over parcels for each catalog:

    1. Linear scan per (catalog, parcel): O(n * T) — up to 10^5 * 2 * 10^5 = 2 * 10^10 checks.
    2. 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^5 catalogs of 2 crates each (T = 2 * 10^5) and n = 10^5 parcels? Visiting every (catalog, parcel) pair still executes K * n = 10^10 iterations and times out!

    Notice the asymmetry in the constraints: K * n can be 10^10, whereas the total number of crate rows T across all catalogs combined is at most 2 * 10^5! That tells us our work must loop over crate rows T, not (catalog, parcel) pairs.

  3. Flip the perspective: count parcels per crate with binary search

    Sort requirements once in non-decreasing order. Now inspect one catalog's sorted capacities c_0 <= c_1 <= ... <= c_(m-1):

    • Which parcels use crate c_0? Every parcel with requirement <= c_0.
    • Which parcels use crate c_1? Every remaining parcel with c_0 < requirement <= c_1.
    • In general, crate c_j packs 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 = 4
    

    Notice two clean shortcuts in that diagram:

    1. Calling Python's bisect_right(sorted_requirements, capacity) finds how many parcels satisfy requirement <= capacity in O(log n) time. Subtracting orders_packed_so_far gives the exact count of parcels landing in capacity!
    2. Instead of summing capacity - requirement parcel by parcel, we sum newly_packed_orders * capacity across the crates to get total_capacity_used, and subtract total_required = sum(requirements) once at the end!
  4. Group crate rows by catalog index

    First we bucket the [set_index, capacity] rows into capacities_by_set, leaving an empty list [] for any catalog index that has no rows. Sorting each bucket is O(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_set
    
  5. Compute 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_requirements and set_capacities are 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 return None so the caller never confuses an ineligible catalog with 0 unused space.

    Why bisect_right instead of bisect_left? Suppose sorted_requirements = [3, 5, 8, 8] and capacity = 8: - bisect_right places the split after both 8s (index 4), packing both 8s into crate 8 with 0 unused space. - bisect_left would stop before the 8s (index 2), mistakenly pushing exact-fit 8s into crate 10!

    What if a catalog lists duplicate capacities like [4, 4, 8]? The second 4 produces orders_fitting_upto_here == orders_packed_so_far, adding 0 * 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_required
    
  6. Pick the winning catalog and trace Example 1

    Finally, we scan set_index from 0 to num_container_sets - 1 and update best_set_index only when waste < 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: 1
    
  7. Complete 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) (or O((n + T) log n + T log T + K) if rows within a catalog are unsorted). Sorting requirements once takes O(n log n) time, grouping T rows into K buckets takes O(K + T) time (plus O(T) for Python's Timsort on already-sorted buckets, or O(T log T) worst-case), and compute_set_waste performs at most one O(log n) bisect_right call per crate row (T rows total) plus one O(K) pass to select the winner. At the maximum bounds that is roughly 3.5 million operations, finishing well under a tenth of a second.
  • Space: O(n + K + T). sorted_requirements holds n integers, and capacities_by_set holds K list headers containing T capacities in total.

Edge cases

  • No eligible catalog: Every catalog's largest capacity is strictly smaller than sorted_requirements[-1], so best_set_index remains -1.
  • Exact fit on the largest parcel (set_capacities[-1] == sorted_requirements[-1]): Eligible because the rule requires capacity >= requirement, so only < disqualifies a catalog.
  • Catalog index with zero rows: len(set_capacities) == 0 returns None immediately rather than raising IndexError or falsely reporting 0 unused space.
  • Exact fits and 0 total unused space: bisect_right includes elements equal to capacity, assigning exact matches 0 slack; returning None (not 0 or -1) for ineligible catalogs keeps 0 distinct from "ineligible".
  • Ties on minimum unused space: Updating best_set_index only 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] gets newly_packed_orders = 0 on its second occurrence, and repeated volumes in [3, 5, 8, 8] are counted together in O(log n) time.
  • 64-bit total unused space: Up to 10^5 parcels of volume 1 packed into 10^9-capacity crates produce ~10^14 unused units, exceeding 32-bit signed int (~2.1 * 10^9); Python int is arbitrary-precision, while C++/Java require long long / long.

Common mistakes

  • Binary-searching crates per parcel (O(K * n log m)): Times out whenever K and n are both 10^5 (for instance, 10^5 catalogs of 2 crates each).
  • Using bisect_left instead of bisect_right: bisect_left counts only parcels strictly < capacity, which pushes exact-fit parcels (requirement == capacity) into the next larger crate (or leaves parcels equal to set_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_used leaves oversized parcels unpacked (0 * capacity) and makes ineligible catalogs look artificially cheap or even negative!
  • Sorting requirements inside the for set_index loop: Turns one O(n log n) sort into O(K * n log n) (~1.7 * 10^11 operations).
  • 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 of sorted_requirements so any slice sum is prefix[r] - prefix[l] in O(1) time) and accumulate newly_packed_orders * capacity - (prefix[upto] - prefix[prev]) per crate. Algebraically those slice sums telescope to total_required, so subtracting total_required once 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 pass sorted(catalogs[s]) directly into compute_set_waste for each s in range(len(catalogs)). Duplicate capacities inside sorted(catalogs[s]) do not even need explicit deduplication because the repeated call to bisect_right yields newly_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 accumulate newly_packed_orders * cost (without subtracting total_required). If you may choose any crate with capacity >= requirement to minimize dollar spend, a larger crate might be cheaper than a smaller one, so first compute suffix-minimum costs cheapest_from_here[j] = min(cost[j:]) from right to left within each catalog and accumulate newly_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_set once in O(T log T + K) time and keep the sorted per-catalog lists in memory; each incoming batch of n parcels then sorts its own requirements and evaluates catalogs. If n is tiny on some batches (n << T / K) while large on others, dispatch dynamically per catalog of size m: binary-search crates per parcel (O(n log m)) when n < m, and binary-search parcels per crate (O(m log n)) when m <= n!

Follow-up questions

Similar questions

More Imc interview questions

All 17 Imc questions →