Drill

ProblemsJavaScript › machines

Which station has the least work

hardmachinesJavaScript

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

leastLoadedStation(jobs: list<Job>, stationCount: int) → int

Solve it in the editor →

Where you start

function leastLoadedStation(jobs, stationCount) {
  
}

Worked examples

CallResult
leastLoadedStation([{"station":0,"hours":10},{"station":1,"hours":5},{"station":0,"hours":2}], 2)1
leastLoadedStation([{"station":0,"hours":3},{"station":1,"hours":3}], 2)0
leastLoadedStation([{"station":5,"hours":10}], 3)0
leastLoadedStation([], 4)0

Hint

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

Reference solution in JavaScript
function leastLoadedStation(jobs, stationCount) {
  if (stationCount <= 0) return 0;
  const totals = new Array(stationCount).fill(0);
  for (const j of jobs) {
    if (j.station < 0 || j.station >= stationCount) continue;
    totals[j.station] += j.hours;
  }
  let best = 0;
  for (let i = 1; i < totals.length; i++) if (totals[i] < totals[best]) best = i;
  return best;
}

The same problem in another language

More machines problems in JavaScript