Minimum Rebuild Cost with Layer Caching
Problem Statement
Given a linear Dockerfile where each instruction has a build cost, and a set of instructions whose inputs changed, compute the total build time knowing that a cached layer is free but any layer at or below the first change must rebuild.
Background
Layers build top to bottom. A layer is rebuilt if it changed or any layer above it was rebuilt (cache invalidation cascades downward). So the first changed index f triggers rebuild of all layers f..n-1; layers 0..f-1 are cached (free). The total build time is the sum of cost[i] for i >= f. If nothing changed, total is 0. Additionally, an optional always set marks layers that never cache (e.g. ADD of a remote URL) — such a layer also forces itself and everything below to rebuild.
Your Task
def rebuild_cost(costs, changed, always=None):
- costs: list of per-layer build costs.
- changed: set/list of indices whose inputs changed.
- always: optional set/list of indices that never cache.
- Return the total rebuild time (int/float).
Input Format
- costs (list of numbers), changed (list of ints), always (list of ints or None).
Output Format
- A number (total rebuild cost).
Sample
print(rebuild_cost([1, 2, 3, 4], [2]))
Output:
7
Example
print(rebuild_cost([1, 2, 3, 4], [2]))
7
- Identify the set of invalid layers by combining the
changedindices with anyalwaysindices; here,changedis andalwaysis empty, so the invalid set is . - Determine the first invalid index by finding the minimum value in the invalid set, which is ; this index marks the start of the rebuild cascade.
- Select the sub-list of costs from index to the end of the list, which corresponds to layers 2 and 3: .
- Calculate the total rebuild cost by summing the selected costs: .
- The final output is 7
Constraints
- The first invalidation index
f= min(changed ∪ always); if empty, cost is 0. - Rebuild all layers
i >= f; sum their costs. alwaysdefaults to empty.