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:
- Single use: Each engine and each freight car may participate in at most one train (unused engines and cars may remain in the yard).
- Weight limit: The combined weight of the train's cars is at most its engine's capacity (
sum(weight) <= locomotives[i]). - Length limit: The combined length of the train's cars is at most
max_car_length(sum(length) <= max_car_length). - 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) <= 61 <= len(cars) <= 141 <= locomotives[i] <= 10^71 <= weight, length <= 10^6for every[weight, length]incars1 <= max_car_length <= 10^71 <= min_cars <= max_cars <= len(cars)
Step-by-step walkthrough
Understand the goal and rules
We have up to
6locomotives (each with a maximum pulling weight capacity) and up to14railcars (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_carsandmax_carsinclusive (and becausemin_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):
- Primary goal: Maximize the number of valid trains assembled.
- 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].- Weight check: sum of car weights
Why brute force and greedy both fail
A direct brute-force search decides, for each of the
nrailcars, which of themlocomotives pulls it (or leaves the car unused). That givesm + 1choices per car, or(m + 1)^ntotal assignments — atm = 6andn = 14,7^14is roughly678 billioncombinations, 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 <= 14is small enough that the total number of railcar subsets is only2^14 = 16,384, which fits easily in a simple array.Key insight 1: always assign the strongest locomotives first
Suppose some valid plan forms
ktrains usingklocomotives from the fleet. What happens if we sort thosekchosen locomotives from strongest to weakest, and line them up against thekstrongest 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 ther-th strongest locomotive in any chosen subset ofk. 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
locomotivesin descending order. - Assign train 1 to the strongest locomotive, train 2 to the second strongest, and so on.
- As soon as step
kcannot form ak-th train, no weaker locomotive later in the sorted list can either, so we canbreakimmediately.
- Sort
Key insight 2: represent car subsets as bitmasks
A bitmask packs a subset of
ncars into one integer from0to2^n - 1, where biti(1 << i) is1if cariis included and0otherwise:4 cars: index 3 2 1 0 mask = 9 -> 0b 1 0 0 1 -> {car 0, car 3}Notice two crucial properties of any
ktrains we have already formed:- What we can form next depends only on which cars are already used, never on how those used cars were split across the earlier
ktrains. - The total length across all
ktrains is simply the sum of lengths of all used cars (subset_length[used_mask]).
So after considering the
kstrongest locomotives, our entire dynamic programming (DP) state is justreachable_masks: the list ofused_maskintegers that can be partitioned intokvalid trains.- What we can form next depends only on which cars are already used, never on how those used cars were split across the earlier
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
0to2^n - 1once. Atn = 14,16,384 * 14is only229,376tiny 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_countEnumerate non-empty subsets of the remaining free cars
Suppose earlier trains used
used_mask. Putting1s on allncars givesall_cars_mask = (1 << num_cars) - 1, so the still-unused cars arefree_mask = all_cars_mask ^ used_mask(XOR turns off every bit already inused_mask). Ifsubset_count[free_mask] < min_cars, we skipused_maskright away.To visit every non-empty subset
train_maskoffree_maskwithout 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_maskjump straight to the next subset offree_mask? Subtracting1clears the lowest1bit oftrain_maskand sets every bit to its right to1;& free_maskmasks off any1bits at positions that were not free, leaving the exact next-smaller subset offree_mask.Across all
used_maskvalues at one locomotive level, every car sits in one of3mutually exclusive buckets — inused_mask, intrain_mask, or in neither — so the inner loop visits at most3^npairs (3^14 = 4,782,969).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 for1train (length50), yet{c1, c2}(length45) leftc0free to unlock[2, 80]at Level 2!Also notice that
best_total_lengthis recomputed from scratch at each level rather than takingmaxwith the previous level, because2trains with smaller total length always outranks1train with larger total length.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:
- Start (0 trains): only the empty car set
{}(bitmask0b0000) is reachable. - Locomotive 1 (capacity 85): it can pull any single car, or two-car sets
{car 0, car 3}(weight60, length50),{car 1, car 2}(weight60, length45),{car 1, car 3}(length40), or{car 2, car 3}(length35), while{car 0, car 1}and{car 0, car 2}exceed length50. So1train is reachable with best length50. - Locomotive 2 (capacity 55): extending
{car 1, car 2}with free{car 0}(weight 45 <= 55, length35) 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 all2^ncar subsets checksnbits per mask (n * 2^nsteps). Then, for each of themsorted locomotives, we check2^nmasks to buildcan_pulland iterate over disjoint(used_mask, train_mask)pairs; since each of thencars is either already used, in the new train, or still unused, there are at most3^nsuch pairs per locomotive (6 * 3^14 ≈ 28.7 millionsimple operations at the maximum constraints). - Space:
O(2^n). We store constant-count arrays of size2^n(16,384atn = 14) for subset weights, lengths, counts,can_pull, and reachable masks.
Edge cases
- No valid train possible (Example 2):
next_reachableis 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, andcount == max_carsare all valid because the rules are inclusive (<=and>=). - Leftover cars forced by
min_cars: with5identical light cars andmin_cars = max_cars = 2, only2trains (4cars) can be formed even if3locomotives are available. - Unsorted locomotives: if
locomotives = [5, 50, 5]and cars weigh40and30, sorting[50, 5, 5]ensures the50-capacity locomotive forms1train before the weak5-capacity locomotive stops the loop. - More trains with shorter total length: if
1train can achieve length11while the best2-train plan only achieves length8,[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 when5cannot pull anything misses the valid train on50, 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_lengthacross levels: if1train reaches length11and2trains only reach8,max(best_total_length, ...)would wrongly return[2, 11]— an impossible combination. - Iterating
train_maskover all subsets instead of subsets offree_mask: allowingused_maskandtrain_maskto overlap assigns the same railcar to two trains. - Recomputing subset weight and length inside the inner loop: summing
ncars inside the3^nloop adds an extra factor ofnand risks timing out.
Alternative approaches
- Memoized recursion with a skip branch: define
best(loco_idx, used_mask)as the optimal(trains, length)fromlocomotives[loco_idx:]givenused_mask, trying either skippingloco_idxor assigning any valid submask offree_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]andused[loco]and maximizingBIG * sum(used) + sum(length * x)(withBIG > sum(all_lengths)) scales well with industrial solvers whenmandngrow past bitmask limits.
Follow-up questions
- How would your approach change if up to
Kengines 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 allmengines into groups of size1toK, sum each group's capacity, deduplicate sorted capacity tuples, and runoptimize_train_assemblyon each. Withm <= 6, there are at most203set partitions total (and only76whenK = 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 the2^Nbitmask state with a count tuple(u_1, u_2, ..., u_t)where0 <= u_i <= count_i; for example,3car categories of ~33cars each produce only34^3 = 39,304states. 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 arrayseen_nextwith a parent dictionaryparent[used_mask | train_mask] = (used_mask, train_mask)recording how each mask was reached. Once the loop finishes, pick the maskbest_maskin the finalreachable_masksthat maximizessubset_length[best_mask], and walk backward through each level'sparentdictionary to read off the exacttrain_mask(and convert its1bits back to car indices) assigned to each engine.
Follow-up questions
- How would your approach change if up to `K` engines could be linked together to pull a single train?
- Suppose there are 100 railcars, all belonging to just a few identical `(weight, length)` categories—how would you redesign the DP state?
- How can you reconstruct the exact engine-to-railcar schedule instead of returning only `[max_trains, max_total_car_length]`?
Similar questions
- Minimum Removals for Pairwise Bridge Load
- Railcar Pricing Endpoint Service and Resilient High-Load Architecture
- Plain-Text Notes CRUD API and Black-Box Testing
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses