AlgoPlusAlgoPlus
Learn/Data Structures & Algorithms
Lesson

Assembly Line Scheduling

Find the fastest route through two parallel assembly lines in one forward pass — O(n).

7 min read Watch it move Build it

A factory has two parallel assembly lines, each with the same n stations in sequence. A product normally flows straight down one line, but between stations it may switch lines for a transfer cost. Each station has its own processing time, and there are entry and exit costs at the ends. Assembly line scheduling finds the route — which line at each station — that finishes fastest. It's a tiny, beautiful DP that runs in a single forward sweep.

The only decision at each station

Arriving at station j on line i, you came from one of just two places: station j-1 on the same line (no transfer), or station j-1 on the other line (pay the transfer cost). Let f[i][j] = the earliest possible time to finish station j on line i. Each value reads only the two values from the previous station, so the whole factory resolves left to right.

  1. 1Entry: f[0][0] = entry[0] + a[0][0] and f[1][0] = entry[1] + a[1][0] (cost to reach and run the first station on each line).
  2. 2For station j on line 0: f[0][j] = a[0][j] + min( f[0][j-1], f[1][j-1] + transfer[1][j-1] ).
  3. 3Symmetrically for line 1: f[1][j] = a[1][j] + min( f[1][j-1], f[0][j-1] + transfer[0][j-1] ).
  4. 4Final answer: min( f[0][n-1] + exit[0], f[1][n-1] + exit[1] ).
Optimal substructure in one line
The fastest way to reach a station is the fastest way to reach *its predecessor* plus this station's cost — there's no benefit in arriving slower earlier. That's why a greedy-looking forward pass is provably optimal here.
function fastestWay(a, t, entry, exit, n) {
  const f = [new Array(n), new Array(n)];
  f[0][0] = entry[0] + a[0][0];
  f[1][0] = entry[1] + a[1][0];
  for (let j = 1; j < n; j++) {
    f[0][j] = a[0][j] + Math.min(f[0][j - 1], f[1][j - 1] + t[1][j - 1]);
    f[1][j] = a[1][j] + Math.min(f[1][j - 1], f[0][j - 1] + t[0][j - 1]);
  }
  return Math.min(f[0][n - 1] + exit[0], f[1][n - 1] + exit[1]);
}
Track the choices to recover the route
Store which line each min chose at every station. After the forward pass, trace those choices backward from the cheaper exit to print the actual line-by-line path — the same traceback idea as LCS.
OperationTimeSpace
Forward pass · two values per station; O(1) extra if you only need the timeO(n)O(n)
Brute force (all paths) · two line choices per stationO(2ⁿ)
Check yourself
At each station, how many predecessors does assembly line scheduling consider?