PIXELBANKv9.1.0
Menu

Problem Statement

Docker reuses cached layers until the first instruction whose inputs changed; everything from there down rebuilds. Given each instruction's cache key for the previous and current build, find the index of the first rebuilt layer.

Background

Builds compare instruction cache keys top to bottom. All layers match the cache until the first index where the current key differs from the previous build's key — that layer and every layer after it are rebuilt. If the current build has more instructions than the previous, the extra tail is new (rebuilt).

Your Task

def first_rebuild(prev_keys, cur_keys):

Return the 0-based index of the first rebuilt layer, or -1 if the build is fully cached (current is a prefix-equal of previous with no extra layers).

Input Format

  • prev_keys, cur_keys (lists of strings).

Output Format

  • An int index or -1.

Sample

print(first_rebuild(["a", "b", "c"], ["a", "b", "x"]))

Output:

2

Example:

Input:
print(first_rebuild(["a", "b", "c"], ["a", "b", "x"]))
Output:
2
Reasoning:
  • Compare the first layer (index 0): the previous key is "a" and the current key is "a". Since they match, the cache is valid for this layer, so we proceed to the next index.
  • Compare the second layer (index 1): the previous key is "b" and the current key is "b". Since they match, the cache remains valid, and we move to the next index.
  • Compare the third layer (index 2): the previous key is "c" and the current key is "x". Since "c" \neq "x", this is the first point of divergence where the inputs have changed.
  • Because a mismatch is found at index 2, all layers from this index onward must be rebuilt, making index 2 the first rebuilt layer.
  • The final output is 2

Constraints:

  • Compare keys by index; first mismatch is the rebuild point.
  • If cur is longer and matches on the shared prefix, the first extra index is the rebuild point.
  • Return -1 when fully cached (no mismatch and len(cur) <= len(prev)).
🔒

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.
First Cache-Invalidated Build Layer - Medium | PixelBank