Repair a Looping Script by Swapping One Instruction
Arrays & HashingAuto-graded · 20 test casesLast updated
Tests simulation, cycle detection, and brute-force search by finding the single jmp/nop swap that lets a small virtual machine terminate cleanly.
Problem
You are given a small script that runs on a toy virtual machine. The machine has a single integer register called the accumulator, initialized to 0, and an instruction pointer (ip) that starts at index 0.
The script supports exactly three instruction types:
acc N— addsNto the accumulator, then moves to the next instruction (ip += 1).jmp N— moves the instruction pointer byNrelative to its current position (ip += N).nop N— does nothing withNand simply advances to the next instruction (ip += 1).
The script is considered to have terminated successfully when the instruction pointer lands exactly one past the last instruction (i.e., ip == len(script)). Any other out-of-range value of ip is an invalid crash, not a successful termination.
Unfortunately, the script contains exactly one corrupted instruction: either a single jmp that should be a nop, or a single nop that should be a jmp. No acc instruction is ever corrupted. As a result, the script may revisit an instruction it has already executed, putting the machine into an infinite loop.
Write a function repair_script(instructions) that identifies the corrupted instruction, corrects it, and returns the value of the accumulator the moment the repaired script terminates successfully.
Note: if the script already terminates without any modification, return the accumulator value from that unmodified run.
Input
instructions: a list of strings, each formatted as"<op> <N>"where<op>isacc,jmp, ornop, and<N>is a signed integer (e.g.,"acc +5","jmp -2","nop +0").
Output
A single integer: the accumulator value after the (possibly repaired) script terminates.
Constraints
1 <= len(instructions) <= 1000- Each argument
Nsatisfies-1000 <= N <= 1000. - Exactly one
jmpornopinstruction is corrupted (or the script already terminates cleanly). - An out-of-range
ip(negative, or greater thanlen(instructions)) is a crash and does not count as successful termination. - Successful termination requires
ip == len(instructions)exactly.
Examples
Example 1
Input: repair_script(['nop +0', 'acc +1', 'jmp +4', 'acc +3', 'jmp -3', 'acc -99', 'acc +1', 'jmp -4', 'acc +6'])
Output: 8
Example 2
Input: repair_script(['nop +2', 'acc +5', 'acc +10'])
Output: 15
Hints
Hint 1
Write a helper that simulates one run of the script and reports whether it terminated cleanly or hit a repeated instruction. A set of visited indices is all you need for cycle detection — the machine is deterministic, so revisiting any index means an infinite loop.
Hint 2
Since at most 1000 instructions can be swapped, you can afford to try each jmp/nop flip one at a time and re-run the simulator for each candidate. That is O(N²) total, which is well within budget for N ≤ 1000.
Hint 3
Check the unmodified script first. If it already terminates, return that result immediately. Otherwise, try flips in index order and return the accumulator from the first run that terminates cleanly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem splits cleanly into two parts: a simulator and a search loop.
Simulator
The machine's control flow depends only on the instruction pointer ip — the accumulator never influences which instruction runs next. That means the machine is fully deterministic: if ip ever reaches a value it has visited before, it will repeat the same sequence forever. So a visited set of instruction indices is a complete cycle detector.
The simulator runs until one of three things happens:
ip == len(program): clean termination — return the accumulator.ipis already invisited: infinite loop — returnNone.ipis out of range (negative or beyondlen(program)): crash — returnNone.
The same function handles both the unmodified run and any candidate swap, by accepting a swap_index parameter. When the current ip equals swap_index, the instruction's opcode is flipped (jmp → nop or nop → jmp) before executing. Passing -1 (which will never equal a valid index) leaves the program unchanged.
Search
There are at most N instructions, and only jmp/nop ones are candidates. For each candidate index, one simulation run costs O(N). Trying all candidates is therefore O(N²) total, which is at most about 10⁶ steps for N = 1000 — trivially fast.
The unmodified program is checked first. If it already terminates cleanly (as in Example 2), its result is returned immediately without attempting any swaps.
Why it is correct
- Loop detection is exact:
ipalone determines all future behavior, so a repeatedipis a guaranteed cycle. - The search is exhaustive: the problem guarantees
accis never corrupted, so the fix must be one of thejmp/nopflips, and every such candidate is tried. - Checking the original run first avoids returning a swapped result when the program was already valid.
Edge cases
jmp +0is a self-loop; the second visit to the same index catches it immediately.- Flipping
nop +0tojmp +0also produces a self-loop, so that candidate correctly fails. - A jump whose target is negative or greater than N counts as a crash (
None), not termination. - Single instruction
["jmp +0"]: flipping tonop +0exits with accumulator0.
Complexity
| Value | |
|---|---|
| Time | O(N²) worst case |
| Space | O(N) for the parsed program and the visited set |
Solution
from typing import List
def repair_script(instructions: List[str]) -> int:
# Parse all instructions once up front.
program = []
for line in instructions:
op, arg = line.split()
program.append((op, int(arg)))
n = len(program)
def run(swap_index: int):
"""
Simulate the program, optionally swapping jmp<->nop at swap_index.
Returns the accumulator on clean termination, or None on a loop/crash.
"""
ip, acc = 0, 0
visited = set()
while ip not in visited and 0 <= ip <= n:
if ip == n:
return acc
visited.add(ip)
op, val = program[ip]
# Apply the swap for the candidate index only.
if ip == swap_index:
op = "nop" if op == "jmp" else "jmp"
if op == "acc":
acc += val
ip += 1
elif op == "jmp":
ip += val
else: # nop
ip += 1
return None # loop detected or out-of-range crash
# Try the unmodified program first.
result = run(-1)
if result is not None:
return result
# Try flipping each jmp/nop in order.
for i, (op, _) in enumerate(program):
if op in ("jmp", "nop"):
result = run(i)
if result is not None:
return result
raise ValueError("No single-instruction swap produces a clean termination.")
O(N) follow-up
If N were much larger, an O(N) approach exists. Build reverse edges for the graph where each index points to its natural successor, then BFS backward from the sink node N to find every index that can reach termination without modification (the "good set"). Walk the original execution path from 0; for each jmp/nop encountered, check whether its flipped successor lands in the good set. The first such index is the corrupted instruction. One final forward simulation collects the accumulator. The correctness argument relies on the fact that if the target's path to N passed through the corrupted index, then the original program would already terminate — a contradiction.