Drill

ProblemsPython › machines

Which station has the least work

hardmachinesPython

Jobs are queued against stations on a line. Find the station currently carrying the fewest hours so the next job can be routed there.

least_loaded_station(jobs: list<Job>, station_count: int) → int

Solve it in the editor →

Where you start

def least_loaded_station(jobs: list[Job], station_count: int) -> int:
    

Worked examples

CallResult
least_loaded_station([Job(station=0, hours=10), Job(station=1, hours=5), Job(station=0, hours=2)], 2)1
least_loaded_station([Job(station=0, hours=3), Job(station=1, hours=3)], 2)0
least_loaded_station([Job(station=5, hours=10)], 3)0
least_loaded_station([], 4)0

Hint

Tally per station in an array, then walk the array keeping a running best index.

Reference solution in Python
def least_loaded_station(jobs: list[Job], station_count: int) -> int:
    if station_count <= 0:
        return 0
    totals = [0] * station_count
    for j in jobs:
        if 0 <= j.station < station_count:
            totals[j.station] += j.hours
    best = 0
    for i in range(1, station_count):
        if totals[i] < totals[best]:
            best = i
    return best

The same problem in another language

More machines problems in Python