PythonStudio
Interview Problems

Circuit Breaker with a Fake Clock

hard · state machine

Given threshold >= 1, cooldown >= 1 and calls [time, success] in nondecreasing integer time, simulate a circuit breaker initially closed with zero failures. In closed state, forward each call; success resets consecutive failures, failure increments them and reaching threshold opens the breaker at that time. While open, block calls before opened_time + cooldown. At or after that boundary permit one atomic half-open probe: success closes and clears failures, failure reopens at the probe time. Calls are sequential and instantaneous. A blocked call MUST NOT consume its supplied outcome or extend cooldown. Return one [forwarded_boolean, resulting_state] per call, with state 'open' or 'closed' (half-open is transient). No real API calls or clock. Examples (JSON; null means Python None): Input: {"threshold": 2, "cooldown": 5, "calls": [[0, false], [1, false], [2, true], [6, true]]} Output: [[true, "closed"], [true, "open"], [false, "open"], [true, "closed"]] Input: {"threshold": 1, "cooldown": 3, "calls": [[0, false], [3, false], [5, true], [6, true]]} Output: [[true, "open"], [true, "open"], [false, "open"], [true, "closed"]]

Starter code

def circuit_breaker(threshold: int, cooldown: int, calls: list[list]) -> list[list]:
    """Simulate closed/open transitions and one recovery probe."""
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python compiler