PIXELBANKv9.1.0
Menu

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:

Input:
print(rebuild_cost([1, 2, 3, 4], [2]))
Output:
7
Reasoning:
  • Identify the set of invalid layers by combining the changed indices with any always indices; here, changed is {2}\{2\} and always is empty, so the invalid set is {2}\{2\}.
  • Determine the first invalid index ff by finding the minimum value in the invalid set, which is f=2f = 2; this index marks the start of the rebuild cascade.
  • Select the sub-list of costs from index ff to the end of the list, which corresponds to layers 2 and 3: [3,4][3, 4].
  • Calculate the total rebuild cost by summing the selected costs: 3+4=73 + 4 = 7.
  • 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.
  • always defaults to empty.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.