Drill

ProblemsJavaScript › patterns

The quickest way to fill the order

hardpatternsSliding windowArraysJavaScript

Crates come off a belt in a fixed order. A picker wants the shortest unbroken run of crates that together hold at least what the order needs.

shortestRunReaching(crates: list<int>, target: int) → int

Solve it in the editor →

Where you start

function shortestRunReaching(crates, target) {
  
}

Worked examples

CallResult
shortestRunReaching([2,3,1,2,4,3], 7)2
shortestRunReaching([1,1,1,1], 4)4
shortestRunReaching([1,1], 5)0
shortestRunReaching([8], 8)1

Hint

Grow the window on the right while it falls short, and shrink it from the left the moment it is enough. Each end only ever moves forward.

Reference solution in JavaScript
function shortestRunReaching(crates, target) {
  if (target <= 0) return 0;
  let left = 0;
  let window = 0;
  let best = 0;
  for (let right = 0; right < crates.length; right += 1) {
    window += crates[right];
    while (window >= target) {
      const span = right - left + 1;
      if (best === 0 || span < best) best = span;
      window -= crates[left];
      left += 1;
    }
  }
  return best;
}

The same problem in another language

More patterns problems in JavaScript