Drill

ProblemsPython › patterns

The quickest way to fill the order

hardpatternsSliding windowArraysPython

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.

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

Solve it in the editor →

Where you start

def shortest_run_reaching(crates: list[int], target: int) -> int:
    

Worked examples

CallResult
shortest_run_reaching([2, 3, 1, 2, 4, 3], 7)2
shortest_run_reaching([1, 1, 1, 1], 4)4
shortest_run_reaching([1, 1], 5)0
shortest_run_reaching([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 Python
def shortest_run_reaching(crates: list[int], target: int) -> int:
    if target <= 0:
        return 0
    left = 0
    window = 0
    best = 0
    for right, crate in enumerate(crates):
        window += crate
        while window >= target:
            span = right - left + 1
            if best == 0 or span < best:
                best = span
            window -= crates[left]
            left += 1
    return best

The same problem in another language

More patterns problems in Python