Drill

ProblemsJava › patterns

The quickest way to fill the order

hardpatternsSliding windowArraysJava

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

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

int shortestRunReaching(List<Integer> crates, int target) {
    
}

Worked examples

CallResult
shortestRunReaching(Main.<Integer>ls(2, 3, 1, 2, 4, 3), 7)2
shortestRunReaching(Main.<Integer>ls(1, 1, 1, 1), 4)4
shortestRunReaching(Main.<Integer>ls(1, 1), 5)0
shortestRunReaching(Main.<Integer>ls(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 Java
int shortestRunReaching(List<Integer> crates, int target) {
    if (target <= 0) return 0;
    int left = 0, window = 0, best = 0;
    for (int right = 0; right < crates.size(); right++) {
        window += crates.get(right);
        while (window >= target) {
            int span = right - left + 1;
            if (best == 0 || span < best) best = span;
            window -= crates.get(left);
            left++;
        }
    }
    return best;
}

The same problem in another language

More patterns problems in Java