Optimal Train Dispatch Under Yard Limits

Hard · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

A rail yard dispatcher wants to form outbound trains from a pool of engines (locomotives) and freight cars (cars). Here locomotives[i] is the maximum weight capacity of engine i, and cars[j] = [weight, length] gives the weight and length of freight car j.

Every assembled train pairs one engine with a subset of freight cars and must obey four rules:

  1. Single use: Each engine and each freight car may participate in at most one train (unused engines and cars may remain in the yard).
  2. Weight limit: The combined weight of the train's cars is at most its engine's capacity (sum(weight) <= locomotives[i]).
  3. Length limit: The combined length of the train's cars is at most max_car_length (sum(length) <= max_car_length).
  4. Consist size: The number of cars on the train lies within [min_cars, max_cars] inclusive (min_cars <= count <= max_cars).

Evaluate dispatch plans in two-stage priority order: 1. First priority: Assemble the largest possible number of valid trains (max_trains). 2. Tie-breaker: Among all plans that form max_trains trains, maximize the sum of lengths of all assigned freight cars across all trains (max_total_car_length).

Implement optimize_train_assembly(locomotives: List[int], cars: List[List[int]], max_car_length: int, min_cars: int, max_cars: int) -> List[int] and return [max_trains, max_total_car_length] (return [0, 0] if no valid train can be built).

Examples

Example 1

Input:
  locomotives    = [85, 55]
  cars           = [[45, 35], [35, 25], [25, 20], [15, 15]]
  max_car_length = 50
  min_cars       = 1
  max_cars       = 2
Output:
  [2, 80]

Walk-through: - Assigning car 1 ([35, 25]) and car 2 ([25, 20]) to the 85-capacity engine uses weight 60 <= 85 and length 45 <= 50. - Assigning car 0 ([45, 35]) to the 55-capacity engine uses weight 45 <= 55 and length 35 <= 50 (leaving car 3 unused). - Both engines run valid trains (max_trains = 2) with combined assigned car length 45 + 35 = 80. Notice that greedily placing {car 0, car 3} (length 50) on the 85-capacity engine would leave only {car 1} (length 25) for the 55-capacity engine, reaching only 75.

Example 2

Input:
  locomotives    = [40, 35]
  cars           = [[30, 20], [25, 25]]
  max_car_length = 60
  min_cars       = 2
  max_cars       = 2
Output:
  [0, 0]

Walk-through: Because min_cars = 2, any valid train must include both available freight cars, whose combined weight is 30 + 25 = 55. Neither engine (40 or 35) can pull 55, so zero trains can be formed.

Constraints

  • 1 <= len(locomotives) <= 6
  • 1 <= len(cars) <= 14
  • 1 <= locomotives[i] <= 10^7
  • 1 <= weight, length <= 10^6 for every [weight, length] in cars
  • 1 <= max_car_length <= 10^7
  • 1 <= min_cars <= max_cars <= len(cars)

Step-by-step walkthrough

  1. Understand the goal and rules

    We have up to 6 locomotives (each with a maximum pulling weight capacity) and up to 14 railcars (each described by [weight, length]). A valid train pairs one locomotive with a group of railcars that satisfies three inclusive checks:

    • Weight check: sum of car weights <= that locomotive's capacity.
    • Length check: sum of car lengths <= max_car_length.
    • Count check: number of cars is between min_cars and max_cars inclusive (and because min_cars >= 1, every train has at least one car).

    No locomotive or railcar may be used in more than one train. Assembly plans are ranked in lexicographic order (dictionary order on pairs: compare the first number, and only compare the second number if there is a tie):

    1. Primary goal: Maximize the number of valid trains assembled.
    2. Tie-breaker: Among plans achieving that maximum train count, maximize the total length of all assigned railcars.

    If not even a single valid train can be formed, we return [0, 0].

  2. Why brute force and greedy both fail

    A direct brute-force search decides, for each of the n railcars, which of the m locomotives pulls it (or leaves the car unused). That gives m + 1 choices per car, or (m + 1)^n total assignments — at m = 6 and n = 14, 7^14 is roughly 678 billion combinations, far too slow.

    A greedy shortcut — letting the strongest locomotive grab the longest legal group of cars first — also fails: the strongest locomotive can swallow up the light cars that a weaker locomotive needed to form a second train, lowering the total train count!

    However, n <= 14 is small enough that the total number of railcar subsets is only 2^14 = 16,384, which fits easily in a simple array.

  3. Key insight 1: always assign the strongest locomotives first

    Suppose some valid plan forms k trains using k locomotives from the fleet. What happens if we sort those k chosen locomotives from strongest to weakest, and line them up against the k strongest locomotives of the entire fleet?

    Whole fleet sorted:      [100,  90,  80,  40]
    Suppose a 2-train plan
    used 90 and 40:          [ 90,       40     ]
    Move trains to top 2:    [100,  90          ]  (100 >= 90 and 90 >= 40, so both still fit!)
    

    The r-th strongest locomotive overall is always at least as strong as the r-th strongest locomotive in any chosen subset of k. Moving each train onto the matching stronger locomotive keeps every weight check valid without changing the number of trains or the cars used.

    This completely removes having to guess which locomotives to use:

    • Sort locomotives in descending order.
    • Assign train 1 to the strongest locomotive, train 2 to the second strongest, and so on.
    • As soon as step k cannot form a k-th train, no weaker locomotive later in the sorted list can either, so we can break immediately.
  4. Key insight 2: represent car subsets as bitmasks

    A bitmask packs a subset of n cars into one integer from 0 to 2^n - 1, where bit i (1 << i) is 1 if car i is included and 0 otherwise:

    4 cars: index   3  2  1  0
    mask = 9  ->  0b 1  0  0  1  ->  {car 0, car 3}
    

    Notice two crucial properties of any k trains we have already formed:

    1. What we can form next depends only on which cars are already used, never on how those used cars were split across the earlier k trains.
    2. The total length across all k trains is simply the sum of lengths of all used cars (subset_length[used_mask]).

    So after considering the k strongest locomotives, our entire dynamic programming (DP) state is just reachable_masks: the list of used_mask integers that can be partitioned into k valid trains.

  5. Precompute weight, length, and count for every car subset

    Before looping over locomotives, we precompute the total weight, total length, and car count of every bitmask from 0 to 2^n - 1 once. At n = 14, 16,384 * 14 is only 229,376 tiny loop iterations:

    from typing import List, Tuple
    
    
    def precompute_car_subsets(cars: List[List[int]]) -> Tuple[List[int], List[int], List[int]]:
        """Precompute total weight, total length, and car count for every car bitmask."""
        num_cars = len(cars)
        num_masks = 1 << num_cars
    
        # subset_weight[mask]: sum of weights of cars whose bit is 1 in mask (e.g. mask=0b0101 -> car 0 + car 2)
        subset_weight = [0] * num_masks
        # subset_length[mask]: sum of lengths of cars whose bit is 1 in mask
        subset_length = [0] * num_masks
        # subset_count[mask]: how many cars are included in mask
        subset_count = [0] * num_masks
    
        for mask in range(num_masks):
            for car_idx in range(num_cars):
                if mask & (1 << car_idx):
                    car_weight = cars[car_idx][0]
                    car_length = cars[car_idx][1]
                    subset_weight[mask] += car_weight
                    subset_length[mask] += car_length
                    subset_count[mask] += 1
    
        return subset_weight, subset_length, subset_count
    
  6. Enumerate non-empty subsets of the remaining free cars

    Suppose earlier trains used used_mask. Putting 1s on all n cars gives all_cars_mask = (1 << num_cars) - 1, so the still-unused cars are free_mask = all_cars_mask ^ used_mask (XOR turns off every bit already in used_mask). If subset_count[free_mask] < min_cars, we skip used_mask right away.

    To visit every non-empty subset train_mask of free_mask without ever touching an already-used car, we use the bitwise submask countdown (train_mask - 1) & free_mask:

    Suppose free_mask = 0b1010 (cars 1 and 3 are free):
    
    Start:    train_mask = 0b1010                              -> {car 1, car 3}
    Step 1:   (0b1010 - 1) & 0b1010 = 0b1001 & 0b1010 = 0b1000 -> {car 3}
    Step 2:   (0b1000 - 1) & 0b1010 = 0b0111 & 0b1010 = 0b0010 -> {car 1}
    Step 3:   (0b0010 - 1) & 0b1010 = 0b0001 & 0b1010 = 0b0000 -> stop!
    

    Why does (train_mask - 1) & free_mask jump straight to the next subset of free_mask? Subtracting 1 clears the lowest 1 bit of train_mask and sets every bit to its right to 1; & free_mask masks off any 1 bits at positions that were not free, leaving the exact next-smaller subset of free_mask.

    Across all used_mask values at one locomotive level, every car sits in one of 3 mutually exclusive buckets — in used_mask, in train_mask, or in neither — so the inner loop visits at most 3^n pairs (3^14 = 4,782,969).

  7. Trace Example 1 level by level

    In Example 1, locomotives = [85, 55], cars = [[45, 35], [35, 25], [25, 20], [15, 15]], max_car_length = 50, min_cars = 1, max_cars = 2:

    Level 0 (0 trains):
      reachable_masks = [0b0000]
    
    Level 1 (locomotive capacity = 85):
      Valid 1-car trains: {c0}, {c1}, {c2}, {c3}
      Valid 2-car trains:
        {c0, c1} -> len 60 > 50 (too long)
        {c0, c2} -> len 55 > 50 (too long)
        {c0, c3} -> wt 45 + 15 = 60 <= 85, len 35 + 15 = 50 <= 50 (valid!)
        {c1, c2} -> wt 35 + 25 = 60 <= 85, len 25 + 20 = 45 <= 50 (valid!)
        {c1, c3} -> wt 35 + 15 = 50 <= 85, len 25 + 15 = 40 <= 50 (valid!)
        {c2, c3} -> wt 25 + 15 = 40 <= 85, len 20 + 15 = 35 <= 50 (valid!)
      trains_formed = 1, best_total_length = 50 (from {c0, c3})
    
    Level 2 (locomotive capacity = 55):
      From used_mask = {c0, c3} (0b1001), free_mask = {c1, c2} (0b0110):
        {c1, c2} has wt 60 > 55 (too heavy for 55!), while {c1} fits -> total length 50 + 25 = 75.
      From used_mask = {c1, c2} (0b0110), free_mask = {c0, c3} (0b1001):
        {c0, c3} has wt 60 > 55 (too heavy), while {c0} (wt 45 <= 55, len 35) fits!
        Combined mask = {c0, c1, c2} (0b0111), total length = 35 + 25 + 20 = 80.
      trains_formed = 2, best_total_length = 80.
    

    Notice how keeping all reachable masks at Level 1 paid off: {c0, c3} looked best for 1 train (length 50), yet {c1, c2} (length 45) left c0 free to unlock [2, 80] at Level 2!

    Also notice that best_total_length is recomputed from scratch at each level rather than taking max with the previous level, because 2 trains with smaller total length always outranks 1 train with larger total length.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def precompute_car_subsets(cars: List[List[int]]) -> Tuple[List[int], List[int], List[int]]:
        """Precompute total weight, total length, and car count for every car bitmask."""
        num_cars = len(cars)
        num_masks = 1 << num_cars
    
        # subset_weight[mask]: sum of weights of cars whose bit is 1 in mask (e.g. mask=0b0101 -> car 0 + car 2)
        subset_weight = [0] * num_masks
        # subset_length[mask]: sum of lengths of cars whose bit is 1 in mask
        subset_length = [0] * num_masks
        # subset_count[mask]: how many cars are included in mask
        subset_count = [0] * num_masks
    
        for mask in range(num_masks):
            for car_idx in range(num_cars):
                if mask & (1 << car_idx):
                    car_weight = cars[car_idx][0]
                    car_length = cars[car_idx][1]
                    subset_weight[mask] += car_weight
                    subset_length[mask] += car_length
                    subset_count[mask] += 1
    
        return subset_weight, subset_length, subset_count
    
    
    def optimize_train_assembly(
        locomotives: List[int],
        cars: List[List[int]],
        max_car_length: int,
        min_cars: int,
        max_cars: int,
    ) -> List[int]:
        num_cars = len(cars)
        num_masks = 1 << num_cars
        all_cars_mask = num_masks - 1
    
        # Phase 1: precompute weight, length, and count for all 2^n subsets of cars once.
        subset_weight, subset_length, subset_count = precompute_car_subsets(cars)
    
        # Sort capacities high-to-low: any k-train plan can always be assigned to the k strongest locomotives.
        sorted_capacities = sorted(locomotives, reverse=True)
    
        # reachable_masks: list of used-car bitmasks that can be partitioned into `trains_formed` valid trains.
        # With 0 trains formed, only the empty car set (mask 0) is reachable.
        reachable_masks = [0]
        trains_formed = 0
        best_total_length = 0
    
        # Phase 2: add one train at a time, starting with the strongest locomotive.
        for capacity in sorted_capacities:
            # can_pull[mask]: True if this locomotive alone can pull car subset `mask` as one valid train.
            # Start at mask = 1 because a train cannot be empty, and use <= because all limits are inclusive.
            can_pull = [False] * num_masks
            for mask in range(1, num_masks):
                within_count = min_cars <= subset_count[mask] <= max_cars
                within_length = subset_length[mask] <= max_car_length
                within_weight = subset_weight[mask] <= capacity
                if within_count and within_length and within_weight:
                    can_pull[mask] = True
    
            # seen_next[mask]: True if `mask` of used cars can be formed across `trains_formed + 1` trains.
            seen_next = [False] * num_masks
            for used_mask in reachable_masks:
                free_mask = all_cars_mask ^ used_mask
                # If fewer than min_cars unused cars remain, no valid train can be formed from free_mask.
                if subset_count[free_mask] < min_cars:
                    continue
    
                train_mask = free_mask
                # Step through every non-empty submask of free_mask without ever touching an already-used car.
                while train_mask > 0:
                    if can_pull[train_mask]:
                        combined_mask = used_mask | train_mask
                        seen_next[combined_mask] = True
                    train_mask = (train_mask - 1) & free_mask
    
            next_reachable: List[int] = []
            for mask in range(num_masks):
                if seen_next[mask]:
                    next_reachable.append(mask)
    
            if not next_reachable:
                # If even this locomotive cannot add another train, no weaker locomotive later in the list can either.
                break
    
            reachable_masks = next_reachable
            trains_formed += 1
            # Recompute from scratch (do not keep an old max): more trains always beats fewer trains, even if shorter.
            best_total_length = 0
            for mask in reachable_masks:
                if subset_length[mask] > best_total_length:
                    best_total_length = subset_length[mask]
    
        return [trains_formed, best_total_length]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of dispatching freight trucks of different weight ratings from a yard: your boss cares first about sending out as many legal trucks as possible, and second (only to break ties) about maximizing the total length of cargo shipped across all dispatched trucks. This two-tier ranking is called lexicographic order, which means we compare the first number (trains) and only look at the second number (total_length) when two plans tie on train count.

A naive search tries assigning each of the 14 railcars to one of the 6 locomotives (or leaving it in the yard), creating 7^14 (roughly 678 billion) combinations. A greedy strategy — letting the strongest locomotive grab the longest legal set of cars first — also fails, because the strong locomotive may consume the light cars that a weaker locomotive needed to form a second train. Instead, we combine two clean ideas: sorting locomotives from strongest to weakest (because any k-train plan can always run on the k strongest locomotives), and dynamic programming (DP) — solving a problem by saving the reachable states of each stage so we never repeat identical work — over bitmasks, where an integer's binary bits record which subset of the 14 cars has been used so far.

Walk through a small example with locomotives = [85, 55], cars = [[45, 35], [35, 25], [25, 20], [15, 15]] ([weight, length]), max_car_length = 50, min_cars = 1, max_cars = 2:

  1. Start (0 trains): only the empty car set {} (bitmask 0b0000) is reachable.
  2. Locomotive 1 (capacity 85): it can pull any single car, or two-car sets {car 0, car 3} (weight 60, length 50), {car 1, car 2} (weight 60, length 45), {car 1, car 3} (length 40), or {car 2, car 3} (length 35), while {car 0, car 1} and {car 0, car 2} exceed length 50. So 1 train is reachable with best length 50.
  3. Locomotive 2 (capacity 55): extending {car 1, car 2} with free {car 0} (weight 45 <= 55, length 35) reaches {car 0, car 1, car 2} (0b0111), achieving [2, 80].

Complexity

Let n be the number of railcars (n <= 14) and m be the number of locomotives (m <= 6).

  • Time: O(n * 2^n + m * 3^n). Precomputing weight, length, and car count across all 2^n car subsets checks n bits per mask (n * 2^n steps). Then, for each of the m sorted locomotives, we check 2^n masks to build can_pull and iterate over disjoint (used_mask, train_mask) pairs; since each of the n cars is either already used, in the new train, or still unused, there are at most 3^n such pairs per locomotive (6 * 3^14 ≈ 28.7 million simple operations at the maximum constraints).
  • Space: O(2^n). We store constant-count arrays of size 2^n (16,384 at n = 14) for subset weights, lengths, counts, can_pull, and reachable masks.

Edge cases

  • No valid train possible (Example 2): next_reachable is empty on the very first locomotive, the loop breaks immediately, and the function returns [0, 0].
  • Exact boundary values: weight == capacity, length == max_car_length, count == min_cars, and count == max_cars are all valid because the rules are inclusive (<= and >=).
  • Leftover cars forced by min_cars: with 5 identical light cars and min_cars = max_cars = 2, only 2 trains (4 cars) can be formed even if 3 locomotives are available.
  • Unsorted locomotives: if locomotives = [5, 50, 5] and cars weigh 40 and 30, sorting [50, 5, 5] ensures the 50-capacity locomotive forms 1 train before the weak 5-capacity locomotive stops the loop.
  • More trains with shorter total length: if 1 train can achieve length 11 while the best 2-train plan only achieves length 8, [2, 8] wins because train count is the primary objective.

Common mistakes

  • Greedy packing on the strongest locomotive: letting the strongest locomotive take its longest valid subset can leave remaining cars too heavy for weaker locomotives, producing fewer trains overall.
  • Unsorted or ascending-sorted locomotives: processing [5, 50] in input order and stopping when 5 cannot pull anything misses the valid train on 50, while sorting ascending ([10, 100]) lets a weak locomotive lock in a tiny train when only one train fits overall. Always sort capacities descending (reverse=True).
  • Keeping a running maximum of best_total_length across levels: if 1 train reaches length 11 and 2 trains only reach 8, max(best_total_length, ...) would wrongly return [2, 11] — an impossible combination.
  • Iterating train_mask over all subsets instead of subsets of free_mask: allowing used_mask and train_mask to overlap assigns the same railcar to two trains.
  • Recomputing subset weight and length inside the inner loop: summing n cars inside the 3^n loop adds an extra factor of n and risks timing out.

Alternative approaches

  • Memoized recursion with a skip branch: define best(loco_idx, used_mask) as the optimal (trains, length) from locomotives[loco_idx:] given used_mask, trying either skipping loco_idx or assigning any valid submask of free_mask. Sorting locomotives descending eliminates the skip branch and gives the cleaner level-by-level DP used here.
  • Branch and bound: a branch-and-bound search explores combinations depth-first while abandoning any partial search path whose optimistic upper bound (e.g., current_trains + min(remaining_locos, free_cars // min_cars)) cannot beat the best answer already found. It shares the same exponential worst case when constraints are loose, but prunes heavily when constraints are tight.
  • Integer linear programming (ILP): an integer linear program optimizes a linear score over whole-number decision variables subject to linear inequalities. Creating binary variables x[loco, car] and used[loco] and maximizing BIG * sum(used) + sum(length * x) (with BIG > sum(all_lengths)) scales well with industrial solvers when m and n grow past bitmask limits.

Follow-up questions

  • How would your approach change if up to K engines could be linked together to pull a single train? In railroading, a consist is a group of engines coupled together to pull one train, acting like a single engine whose capacity is the sum of their capacities. Because our DP already allows any consist at the end of the sorted list to stay idle (making an unused engine equivalent to a 1-engine consist that gets no train), we can enumerate every way to partition all m engines into groups of size 1 to K, sum each group's capacity, deduplicate sorted capacity tuples, and run optimize_train_assembly on each. With m <= 6, there are at most 203 set partitions total (and only 76 when K = 2), so running the fast DP across deduplicated capacity lists stays practical.
  • Suppose there are 100 railcars, all belonging to just a few identical (weight, length) categories—how would you redesign the DP state? Because cars of the same category are interchangeable, we no longer care which specific car of a category was used — only how many cars of each category have been used so far. Replace the 2^N bitmask state with a count tuple (u_1, u_2, ..., u_t) where 0 <= u_i <= count_i; for example, 3 car categories of ~33 cars each produce only 34^3 = 39,304 states. At each sorted engine, transition by choosing a train composition (d_1, ..., d_t) of remaining cars (d_i <= count_i - u_i) that satisfies the count, length, and weight rules.
  • How can you reconstruct the exact engine-to-railcar schedule instead of returning only [max_trains, max_total_car_length]? Sort (capacity, original_loco_index) pairs descending so you keep track of each engine's original index, and at each level replace the boolean array seen_next with a parent dictionary parent[used_mask | train_mask] = (used_mask, train_mask) recording how each mask was reached. Once the loop finishes, pick the mask best_mask in the final reachable_masks that maximizes subset_length[best_mask], and walk backward through each level's parent dictionary to read off the exact train_mask (and convert its 1 bits back to car indices) assigned to each engine.

Follow-up questions

Similar questions

More Bnsf interview questions

All 4 Bnsf questions →