{"id":"first-bad-version","title":"First Bad Version","difficulty":"easy","patterns":["binary-search"],"primaryConcept":"binary-search-basics","concepts":["binary-search-basics"],"problemForm":"intro","companies":["Meta","Google","Amazon","Microsoft"],"category":"searching-sorting","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"two-scalars","primaryParam":"n","secondaryParam":"bad","sizeMetric":"scalar","constraints":["positive-range","bad-within-range","first-true-boundary"],"sizes":[1,10,1000,1000000]},"description":"You are testing product versions numbered from `1` to `n`. Once a version is bad, every later version is also bad.\n\nTraceCode supplies `bad`, the first bad version, so the helper `isBadVersion(version, bad)` can simulate the product API. Return the first bad version using as few checks as possible.\n\nRequirements:\n- `1 <= bad <= n`.\n- You should not scan every version.\n- Your solution should run in O(log n) time.","requiredComplexity":[{"metric":"time","bound":"O(log n)","scope":"function","functions":["firstBadVersion"],"case":"worst","enforcement":"hard","reason":"The prompt asks for the first true boundary with as few API checks as possible."}],"examples":[{"input":"n = 5, bad = 4","output":"4","explanation":"Versions 1, 2, and 3 are good. Versions 4 and 5 are bad."},{"input":"n = 1, bad = 1","output":"1","explanation":"There is only one version, and it is bad."},{"input":"n = 10, bad = 10","output":"10","explanation":"The first bad version can be the last version."}],"constraints":[{"id":"1-n-2-31-1","text":"1 <= n <= 2^31 - 1"},{"id":"1-bad-n","text":"1 <= bad <= n"},{"id":"isbadversion-version-bad-returns-true-exactly-when-version-bad","text":"isBadVersion(version, bad) returns true exactly when version >= bad"}],"starterCode":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        # Call the helper as self.isBadVersion(version, bad)\n        # Your code here\n        pass","functionName":"firstBadVersion","testCases":[{"id":"1","input":{"n":5,"bad":4},"expected":4,"description":"Standard first-true boundary."},{"id":"2","input":{"n":1,"bad":1},"expected":1,"description":"Single version."},{"id":"3","input":{"n":2,"bad":1},"expected":1,"description":"First version is already bad."},{"id":"4","input":{"n":10,"bad":10},"expected":10,"description":"Last version is the first bad version."},{"id":"5","input":{"n":100,"bad":37},"expected":37,"description":"Interior boundary in a larger range."},{"id":"h1","input":{"n":1000000,"bad":765432},"expected":765432,"description":"Large range requiring logarithmic search."},{"id":"h2","input":{"n":16,"bad":8},"expected":8,"description":"Power-of-two range."},{"id":"h3","input":{"n":3,"bad":2},"expected":2,"description":"Small range with middle boundary."},{"id":"h4","input":{"n":2,"bad":2},"expected":2},{"id":"h5","input":{"n":50,"bad":49},"expected":49}],"hints":[{"level":1,"content":"Ask whether the midpoint version is bad. If it is, the first bad version is at mid or to the left.","revealPattern":false},{"level":2,"content":"Keep a search window over version numbers and use `while left < right` so the answer remains inside the window.","revealPattern":true},{"level":3,"content":"When `isBadVersion(mid, bad)` is true, keep `mid` by setting `right = mid`; otherwise set `left = mid + 1`.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Choose the approach whose number of API checks matches the constraint.","approaches":[{"id":"linear-check","name":"Ask about every version in order","summary":"Call isBadVersion on version 1, then 2, and so on, stopping at the first true result.","decisionReason":"It finds the boundary, but with n up to two billion it can call the API n times, which the prompt rules out.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["Up to n API calls, O(1) space."],"isOptimal":false},{"id":"binary-boundary","name":"Halve the version range each check","summary":"Probe the middle version, then keep only the side that can still hold the first bad version.","decisionReason":"Each API result discards half of the remaining versions, so the boundary is found in about log2(n) checks.","complexity":{"time":"O(log n)","space":"O(1)"},"tradeoffs":["About log2(n) API calls, O(1) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-bounds","title":"Initialize the version window","description":"Start the search with every possible version still inside the window.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"initializes_search_bounds","scope":"init-pointers","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Starting at version 0","Using `n - 1` as the upper bound even though versions are 1-indexed"],"hint":"The first possible bad version is 1, and the last possible bad version is n.","semanticSpec":{"intent":"Initialize the binary-search bounds over the full version range.","doneWhen":"The lower bound starts at 1 and the upper bound starts at n before the loop.","shouldFailWhen":"This step should fail if either bound is missing, off by one, or initialized after midpoint probing.","roles":["left boundary","right boundary","version range"],"mustProve":["The search starts at the first version.","The search includes the last version."],"mustNotAccept":["A zero-indexed version window.","A partial version range."],"proofSnippets":[{"id":"py-first-bad-version-init-bounds","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n"}]}},{"id":"loop-window","title":"Loop while multiple candidates remain","description":"Continue the search until the version window collapses to one candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"maintains_search_window","scope":"while-condition","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using a loop that can skip the remaining candidate","Looping over every version"],"hint":"For a first-true boundary search, `while left < right` keeps one candidate at exit.","semanticSpec":{"intent":"Maintain a narrowing search window over version numbers.","doneWhen":"The loop condition compares the active search bounds.","shouldFailWhen":"This step should fail if the loop ignores the search bounds or scans linearly.","roles":["search window","loop guard"],"mustProve":["The loop is controlled by the two boundary variables."],"mustNotAccept":["A fixed-count loop over versions.","A loop that does not use both bounds."],"proofSnippets":[{"id":"py-first-bad-version-loop-window","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n\n        while left < right:\n            pass"}]}},{"id":"calculate-mid","title":"Probe the midpoint version","description":"Compute a midpoint from the current version bounds each iteration.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"computes_midpoint_from_bounds","scope":"calculate-mid","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using normal division instead of integer division","Computing mid from the original n every time"],"hint":"Use `left + (right - left) // 2` or an equivalent integer midpoint.","semanticSpec":{"intent":"Derive the midpoint version from the current search bounds.","doneWhen":"Each loop iteration computes a midpoint that depends on both active bounds.","shouldFailWhen":"This step should fail if the midpoint is constant or only depends on one bound.","roles":["left boundary","right boundary","midpoint version"],"mustProve":["The midpoint is calculated inside the search loop.","The midpoint uses both bounds."],"mustNotAccept":["A fixed probe version.","Linear advancement by one version."],"proofSnippets":[{"id":"py-first-bad-version-calculate-mid","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n\n        while left < right:\n            mid = left + (right - left) // 2"}]}},{"id":"check-version","title":"Check the midpoint version","description":"Use the API predicate to decide whether the midpoint is already bad.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"branches_on_midpoint_boundary_predicate","scope":"check-boundary-predicate","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Checking `bad` directly instead of probing the midpoint","Calling the API on left or right instead of mid"],"hint":"The branch should ask whether `mid` is bad.","semanticSpec":{"intent":"Branch on a midpoint-derived boundary predicate.","doneWhen":"The code calls the bad-version predicate with the midpoint and branches on that result.","shouldFailWhen":"This step should fail if the predicate is not tied to the midpoint probe.","roles":["midpoint version","bad-version predicate"],"mustProve":["The predicate check uses the midpoint version.","The predicate branch controls the next bound update."],"mustNotAccept":["A branch that ignores the midpoint.","A direct return without an API check."],"proofSnippets":[{"id":"py-first-bad-version-check-version","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n\n        while left < right:\n            mid = left + (right - left) // 2\n            if isBadVersion(mid, bad):\n                pass"}]}},{"id":"narrow-window","title":"Keep the first bad candidate","description":"If mid is bad, keep it by moving right to mid; otherwise move left past mid.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"narrows_bounds_around_midpoint","scope":"adjust-direct-boundary","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using `right = mid - 1` and discarding a possible first bad version","Moving the wrong bound after a good midpoint"],"hint":"A bad midpoint might be the first bad version, so do not discard it.","semanticSpec":{"intent":"Narrow the direct-boundary search window without dropping the answer.","doneWhen":"Bad midpoint checks move the upper bound to mid, and good midpoint checks move the lower bound to mid + 1.","shouldFailWhen":"This step should fail if branch directions are reversed or if a bad midpoint is excluded.","roles":["predicate branch","lower boundary","upper boundary","midpoint version"],"mustProve":["The predicate branch controls both bound updates.","The true branch keeps mid as a candidate.","The false branch excludes mid by advancing left."],"mustNotAccept":["Discarding a bad midpoint with `right = mid - 1`.","Using `left = mid` after a good midpoint."],"proofSnippets":[{"id":"py-first-bad-version-narrow-window","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n\n        while left < right:\n            mid = left + (right - left) // 2\n            if isBadVersion(mid, bad):\n                right = mid\n            else:\n                left = mid + 1"}]}},{"id":"return-boundary","title":"Return the collapsed boundary","description":"Return the remaining version once the search window has collapsed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"returns_search_boundary","scope":"return-boundary","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Returning the last midpoint","Returning inside the loop before the boundary collapses"],"hint":"When the loop ends, left and right point to the first bad version.","semanticSpec":{"intent":"Return the final binary-search boundary.","doneWhen":"The function returns the collapsed search boundary after the loop.","shouldFailWhen":"This step should fail if the code returns a stale midpoint, API result, or constant.","roles":["collapsed boundary","first bad version"],"mustProve":["The return happens after boundary narrowing.","The returned value is the remaining search boundary."],"mustNotAccept":["Returning `mid` after the loop.","Returning a boolean API result."],"proofSnippets":[{"id":"py-first-bad-version-return-boundary","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n\n        while left < right:\n            mid = left + (right - left) // 2\n            if isBadVersion(mid, bad):\n                right = mid\n            else:\n                left = mid + 1\n        return left"}]}}],"slides":[{"id":"opener","chapter":"The slow way","kind":"info","eyebrow":"Understand the task","title":"Find the first version that broke","workspacePanel":"problem","body":["Versions run 1 to n. You can ask isBadVersion(v), and the job is to find the first bad version with as few calls as possible.","Once one version is bad, every later version is bad too. One call therefore rules out a whole side of the remaining versions."]},{"id":"brute-force","chapter":"The slow way","kind":"code-trace","eyebrow":"The obvious attempt","title":"Ask every version from the start","summary":"The first idea: call the API on version 1, then 2, then 3, until one comes back true. The first true answer is the boundary.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def firstBadVersion(n: int, bad: int) -> int:\n    version = 1\n    while version <= n:\n        if isBadVersion(version, bad):\n            return version\n        version = version + 1\n    return n","typeContext":{"externalFunctions":{"isBadVersion":{"params":["int","int"],"returns":"bool"}}},"steps":[{"id":"scan-1","title":"Ask about version 1","summary":"isBadVersion(1) is false. Version 1 is good, so move on.","codeLine":4,"state":{"nums":[1,2,3,4,5,6,7,8],"current":0,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"scan-2","title":"Ask about version 2","summary":"isBadVersion(2) is false, so the scan keeps walking.","codeLine":4,"state":{"nums":[1,2,3,4,5,6,7,8],"current":1,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"scan-3","title":"Ask about version 3","summary":"isBadVersion(3) is false. Three calls in and nothing yet.","codeLine":4,"state":{"nums":[1,2,3,4,5,6,7,8],"current":2,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"scan-4","title":"Ask about version 4","summary":"isBadVersion(4) is false. The scan only ever advances one step.","codeLine":4,"state":{"nums":[1,2,3,4,5,6,7,8],"current":3,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"scan-5","title":"Ask about version 5","summary":"isBadVersion(5) is false. The break is next, but the scan had to spend five calls to get here.","codeLine":4,"state":{"nums":[1,2,3,4,5,6,7,8],"current":4,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"scan-6","title":"Version 6 finally answers true","summary":"isBadVersion(6) is true, so the scan returns 6 after six calls.","codeLine":5,"state":{"nums":[1,2,3,4,5,6,7,8],"current":5,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let version = 1;\nwhile (version <= n) {\n    if (isBadVersion(version, bad)) {\n        return version;\n    }\n    version = version + 1;\n}\nreturn n;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":6,"7":8},"statementBundles":{"5":{"startLine":4,"endLine":5},"6":{"startLine":6,"endLine":7}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let version = 1;\nwhile (version <= n) {\n    if (isBadVersion(version, bad)) {\n        return version;\n    }\n    version = version + 1;\n}\nreturn n;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":6,"7":8},"statementBundles":{"5":{"startLine":4,"endLine":5},"6":{"startLine":6,"endLine":7}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int version = 1;\nwhile (version <= n) {\n    if (IsBadVersion(version, bad)) {\n        return version;\n    }\n    version = version + 1;\n}\nreturn n;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":6,"7":8},"statementBundles":{"5":{"startLine":4,"endLine":5},"6":{"startLine":6,"endLine":7}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int version = 1;\nwhile (version <= n) {\n    if (is_bad_version(version, bad)) {\n        return version;\n    }\n    version = version + 1;\n}\nreturn n;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":6,"7":8},"statementBundles":{"5":{"startLine":4,"endLine":5},"6":{"startLine":6,"endLine":7}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int version = 1;\nwhile (version <= n) {\n    if (isBadVersion(version, bad)) {\n        return version;\n    }\n    version = version + 1;\n}\nreturn n;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":6,"7":8},"statementBundles":{"5":{"startLine":4,"endLine":5},"6":{"startLine":6,"endLine":7}}}}}},{"id":"brute-force-cost","chapter":"The slow way","kind":"case-probe","eyebrow":"Count the calls","title":"How many API calls can this scan make?","summary":"The break can sit anywhere in 1..n, including the last version.","workspacePanel":"trace","options":[{"id":"up-to-n","label":"Up to n calls, one per version","rationale":"If the first bad version is n, the scan asks about every earlier version before reaching it, which is n calls for a range of two billion.","isCorrect":true},{"id":"about-half","label":"About n / 2 calls on average","rationale":"An average is not the bound the prompt cares about; the worst case is still proportional to n, which the O(log n) requirement rules out.","isCorrect":false},{"id":"constant","label":"A fixed handful of calls","rationale":"The scan advances one version per call, so the call count grows with the range, not with a constant.","isCorrect":false}],"answer":"Up to n calls. When the break is at the last version, the scan asks about every version before it, which is far too many for n near two billion."},{"id":"one-check-payoff","chapter":"The trick","kind":"case-probe","eyebrow":"Spend one call well","title":"What does one isBadVersion answer settle?","summary":"Versions 1..8, and isBadVersion(4) comes back false.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"one-check","state":{"nums":[1,2,3,4,5,6,7,8],"left":0,"right":7,"mid":3,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}]},"options":[{"id":"left-side-good","label":"Every version up to 4 is good","rationale":"Bad answers never flip back to good, so a false at 4 means 1 through 4 are all good and the first bad version is past 4.","isCorrect":true},{"id":"only-four","label":"Only that version 4 is good","rationale":"The flip-once order carries more: a false at 4 also clears every version before it.","isCorrect":false},{"id":"nothing-useful","label":"Nothing, until a true answer appears","rationale":"A false answer already deletes a whole side. Each call settles half the range, which is the entire point.","isCorrect":false}],"answer":"A false at version 4 proves 1 through 4 are all good. One call discards four versions at once, so the search can halve the range instead of stepping through it."},{"id":"keep-mid-probe","chapter":"The trick","kind":"case-probe","eyebrow":"Handle a bad probe","title":"When a midpoint is bad, which side do you keep?","summary":"Versions 5..8 remain, and isBadVersion(6) comes back true.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bad-probe","state":{"nums":[1,2,3,4,5,6,7,8],"left":4,"right":7,"mid":5,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}]},"options":[{"id":"keep-mid","label":"Keep 5 through 6, with 6 still in the window","rationale":"Version 6 is bad, but nothing yet proves 6 is not the first bad version, so it has to stay a candidate.","isCorrect":true},{"id":"drop-mid","label":"Keep 5 through 5, dropping 6","rationale":"Dropping 6 assumes an earlier bad version exists, but 6 is the first version known to be bad and could be the answer.","isCorrect":false},{"id":"keep-right","label":"Keep 7 through 8, the versions after 6","rationale":"Versions after a bad one are also bad but later, so they can never be the first bad version. The answer is at 6 or earlier.","isCorrect":false}],"answer":"A bad version 6 might still be the earliest bad version, so keep it: the window narrows to 5 through 6 rather than discarding 6."},{"id":"approach-bridge","chapter":"The trick","kind":"info","eyebrow":"Name the moves","title":"Halve the range, keep a bad probe","summary":"Two moves carry the whole search.","ctaLabel":"Trace it","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bridge","state":{"nums":[1,2,3,4,5,6,7,8],"left":0,"right":7,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}]},"body":["Hold a window of versions that could still be the first bad one, starting as the whole range 1 to n.","Probe the middle version. A good probe means the answer is strictly later, so move left past it; a bad probe might itself be the answer, so move right onto it and keep it."]},{"id":"trace","chapter":"Trace","kind":"dry-run","eyebrow":"Trace the state","title":"Trace n = 8 with the break at version 6","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"probe-4","state":{"nums":[1,2,3,4,5,6,7,8],"left":0,"right":7,"mid":3,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"probe-6","state":{"nums":[1,2,3,4,5,6,7,8],"left":4,"right":7,"mid":5,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"probe-5","state":{"nums":[1,2,3,4,5,6,7,8],"left":4,"right":5,"mid":4,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"collapse","state":{"nums":[1,2,3,4,5,6,7,8],"left":5,"right":5,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}]},"beats":[{"id":"probe-4","figure":"setup","title":"Where does left go after this probe?","summary":"One false answer is about to delete half the range in a single step.","prompt":"The window is the whole range 1 to 8, the midpoint is version 4, and isBadVersion(4) comes back false.","options":[{"id":"left-to-5","label":"left moves to 5","rationale":"A good version 4 clears 1 through 4, so the earliest bad version is 5 or later and the window starts at 5.","isCorrect":true},{"id":"right-to-4","label":"right moves to 4","rationale":"That would keep version 4, but a false answer proves 4 is good and cannot be the first bad version.","isCorrect":false},{"id":"left-to-4","label":"left moves to 4","rationale":"Keeping 4 reprobes a version already proven good and can stall the search.","isCorrect":false}],"answer":"left becomes 5. Version 4 is good, so the first bad version must be in 5 through 8."},{"id":"probe-6","figure":"setup","title":"Where does right go after this probe?","summary":"This is the move that drops the bad midpoint or saves it; only one is safe.","prompt":"The window is 5 through 8, the midpoint is version 6, and isBadVersion(6) comes back true.","options":[{"id":"right-to-6","label":"right moves to 6, keeping it","rationale":"Version 6 is bad but nothing earlier is known bad yet, so 6 stays a candidate and the window becomes 5 through 6.","isCorrect":true},{"id":"right-to-5","label":"right moves to 5, dropping 6","rationale":"That discards 6, but 6 is the first version known to be bad and could be the answer.","isCorrect":false},{"id":"left-to-7","label":"left moves to 7","rationale":"Versions after 6 are bad but later, so none of them can be the first bad version.","isCorrect":false}],"answer":"right becomes 6. A bad version 6 might be the earliest bad version, so it stays in the window, now 5 through 6."},{"id":"probe-5","figure":"setup","title":"What remains in the window after this probe?","summary":"One candidate is about to fall, and the search ends the moment it does.","prompt":"The window is 5 through 6, the midpoint rounds down to version 5, and isBadVersion(5) comes back false.","options":[{"id":"only-6","label":"left moves to 6, leaving only version 6","rationale":"Version 5 is good, so left advances past it and the window collapses onto 6, the kept bad candidate.","isCorrect":true},{"id":"only-5","label":"right moves to 5, leaving only version 5","rationale":"Version 5 answered false, so it is good and cannot be the boundary.","isCorrect":false},{"id":"both-stay","label":"Both versions stay","rationale":"A good probe always removes itself and its side, so the window must shrink here.","isCorrect":false}],"answer":"left becomes 6. Version 5 is good, so only version 6 remains, and 6 is the answer."},{"id":"collapse","figure":"setup","title":"left and right both reach 6: what made 6 the answer?","summary":"The window has collapsed to a single version.","prompt":"The search is about to return.","options":[{"id":"survivor","label":"Every other version was ruled good or ruled too late","rationale":"Good probes deleted 1 through 5, later-bad versions 7 and 8 were never candidates, and the one bad probe kept 6.","isCorrect":true},{"id":"last-probe","label":"It was simply the last version probed","rationale":"The answer is the version that survived every cut, not whichever happened to be probed last.","isCorrect":false},{"id":"midpoint-rule","label":"The midpoint always lands on the answer","rationale":"Midpoints landed on 4, 6, and 5; the survivor is decided by the window, not by where mid fell.","isCorrect":false}],"answer":"Version 6 is the only candidate left after good probes deleted the earlier versions and the bad probe at 6 kept it in the window."}]},{"id":"drop-mid-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could a bad midpoint just be cut with right = mid - 1?","summary":"Cutting the bad midpoint out with right = mid - 1 looks like the same shrink, and it even halves the range. But it throws away the version it just learned was bad. Watch it answer a range where that version is the boundary.","workspacePanel":"trace","pitfall":"The code below moves right to mid - 1 after a bad probe, dropping the midpoint instead of keeping it as a candidate.","whyItMatters":"A bad midpoint is the only version so far proven bad, so it must stay in the window: use right = mid after a bad probe and left = mid + 1 after a good one.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"left, right = 1, n\nwhile left < right:\n    mid = left + (right - left) // 2\n    if isBadVersion(mid, bad):\n        right = mid - 1\n    else:\n        left = mid + 1\nreturn left","typeContext":{"externalFunctions":{"isBadVersion":{"params":["int","int"],"returns":"bool"}}},"steps":[{"id":"pf-start","title":"Search versions 1 through 7","summary":"The break is at version 4, so versions 4 through 7 are bad. The first midpoint is version 4.","codeLine":3,"state":{"nums":[1,2,3,4,5,6,7],"left":0,"right":6,"mid":3,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"pf-bad-probe","title":"Version 4 is bad","summary":"isBadVersion(4) is true. Version 4 is the first version known to be bad, so it could be the answer.","codeLine":4,"state":{"nums":[1,2,3,4,5,6,7],"left":0,"right":6,"mid":3,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"pf-drop-mid","title":"right = mid - 1 deletes version 4","summary":"right jumps to 3, so version 4 is gone from the window even though it was the only known bad version.","codeLine":5,"state":{"nums":[1,2,3,4,5,6,7],"left":0,"right":2,"mid":3,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"pf-good-probe","title":"The next midpoint is version 2","summary":"The window is 1 through 3, so mid is 2. isBadVersion(2) is false, so left advances to 3.","codeLine":7,"state":{"nums":[1,2,3,4,5,6,7],"left":0,"right":2,"mid":1,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}},{"id":"pf-wrong-return","title":"The window collapses on version 3","summary":"left and right meet at 3, so the code returns 3. But isBadVersion(3) is false, so version 3 is good: the answer should have been 4.","codeLine":8,"state":{"nums":[1,2,3,4,5,6,7],"left":2,"right":2,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let [left, right] = [1, n];\nwhile (left < right) {\n    const mid = left + Math.floor((right - left) / 2);\n    if (isBadVersion(mid, bad)) {\n        right = mid - 1;\n    } else {\n        left = mid + 1;\n    }\n}\nreturn left;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"7":{"startLine":7,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let [left, right] = [1, n];\nwhile (left < right) {\n    const mid = left + Math.floor((right - left) / 2);\n    if (isBadVersion(mid, bad)) {\n        right = mid - 1;\n    } else {\n        left = mid + 1;\n    }\n}\nreturn left;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"7":{"startLine":7,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int left = 1;\nint right = n;\nwhile (left < right) {\n    int mid = left + Math.floorDiv((right - left), 2);\n    if (isBadVersion(mid, bad)) {\n        right = mid - 1;\n    } else {\n        left = mid + 1;\n    }\n}\nreturn left;","lineMap":{"1":1,"2":3,"3":4,"4":5,"5":6,"6":7,"7":8,"8":11},"statementBundles":{"1":{"startLine":1,"endLine":2},"7":{"startLine":8,"endLine":10}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"var (left, right) = (1, n);\nwhile (left < right) {\n    int mid = left + (right - left) / 2;\n    if (IsBadVersion(mid, bad)) {\n        right = mid - 1;\n    } else {\n        left = mid + 1;\n    }\n}\nreturn left;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"7":{"startLine":7,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int left = 1;\nint right = n;\nwhile (left < right) {\n    int mid = left + ((right - left) / 2);\n    if (is_bad_version(mid, bad)) {\n        right = mid - 1;\n    } else {\n        left = mid + 1;\n    }\n}\nreturn left;","lineMap":{"1":1,"2":3,"3":4,"4":5,"5":6,"6":7,"7":8,"8":11},"statementBundles":{"1":{"startLine":1,"endLine":2},"7":{"startLine":8,"endLine":10}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"A boundary search is only as good as the ranges that press on its ends.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"nums":[1,2,3,4],"left":0,"right":3,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}]},"body":["Three ranges press on the edges: a single version, a break at the very first version, and a break at the very last version.","If the two moves are right, each of these should fall out without a special case."]},{"id":"edge-single","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"With one version, how many API calls run?","summary":"n = 1, bad = 1, so left and right both start at 1.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single","state":{"nums":[1],"left":0,"right":0,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}]},"options":[{"id":"zero","label":"Zero, the loop never runs","rationale":"left < right is already false with both at 1, so the body is skipped and 1 is returned without any probe.","isCorrect":true},{"id":"one","label":"One, to confirm version 1 is bad","rationale":"The constraint already guarantees a bad version exists in 1..1, so the single survivor needs no probe.","isCorrect":false},{"id":"loops-forever","label":"It loops forever on version 1","rationale":"Because the guard is strict, a window of one stops immediately rather than spinning.","isCorrect":false}],"answer":"Zero calls. With left and right both 1, left < right is false, so the loop is skipped and version 1 is returned directly."},{"id":"edge-first-bad","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"When version 1 is the break, can it be lost?","summary":"n = 4, bad = 1, so isBadVersion is true for every version including the first.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-bad","state":{"nums":[1,2,3,4],"left":0,"right":3,"mid":1,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}]},"options":[{"id":"right-walks-down","label":"No: each bad probe keeps mid, walking right down to 1","rationale":"Every probe is bad, so right keeps moving onto mid, and keeping mid means the window shrinks toward 1 without skipping it.","isCorrect":true},{"id":"skips-one","label":"Yes: the first probe is version 2, so version 1 is skipped","rationale":"A bad probe at 2 sets right to 2, keeping version 1 inside the window rather than excluding it.","isCorrect":false},{"id":"returns-2","label":"Yes: it returns 2 because that is the first midpoint","rationale":"The midpoint is not the answer; bad probes keep narrowing right until only version 1 remains.","isCorrect":false}],"answer":"Version 1 is safe. Because bad probes keep mid, right walks down through the window until it lands on 1, which is returned."},{"id":"edge-last-bad","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"When only the last version is bad, what reaches it?","summary":"n = 4, bad = 4: version 2 already answered false, so left has advanced past it.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"last-bad","state":{"nums":[1,2,3,4],"left":2,"right":3,"mid":2,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}]},"options":[{"id":"good-advances","label":"Good probes push left up until only version 4 is left","rationale":"Versions 1, 2, and 3 each answer false, so left keeps advancing past mid until the window collapses on 4.","isCorrect":true},{"id":"stalls-at-3","label":"The search stalls once the window is 3 through 4","rationale":"A good probe at 3 advances left to 4, so the window does not stall; it collapses onto 4.","isCorrect":false},{"id":"never-checks-4","label":"Version 4 is never reached because mid stays below it","rationale":"Good probes move left up past each mid, so the window is driven onto version 4 as the last survivor.","isCorrect":false}],"answer":"Good probes keep advancing left past each midpoint, so the window collapses on version 4, which is returned."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Everything hinges on one move: a bad probe keeps its own version.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready","state":{"nums":[1,2,3,4,5,6,7,8],"left":0,"right":7,"labels":{"nums":"versions","left":"left","right":"right","mid":"mid"}}}]},"body":["Set the window to the whole range, probe the middle version while more than one candidate remains, and move toward the version that survives.","A good probe sends the window strictly later; a bad probe keeps its own version as a possible answer. Return the version the window collapses onto."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the boundary search","summary":"Now write it: set the window to the whole range 1 to n, loop while more than one candidate is left, probe the middle version, then on a bad probe keep mid by moving right onto it and on a good probe move left past it, and return the version the window collapses onto.","workspacePanel":"code","checkpoints":[{"id":"init-bounds","title":"Initialize the version window","description":"Start the search with every possible version still inside the window.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"initializes_search_bounds","scope":"init-pointers","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Starting at version 0","Using `n - 1` as the upper bound even though versions are 1-indexed"],"hint":"The first possible bad version is 1, and the last possible bad version is n.","semanticSpec":{"intent":"Initialize the binary-search bounds over the full version range.","doneWhen":"The lower bound starts at 1 and the upper bound starts at n before the loop.","shouldFailWhen":"This step should fail if either bound is missing, off by one, or initialized after midpoint probing.","roles":["left boundary","right boundary","version range"],"mustProve":["The search starts at the first version.","The search includes the last version."],"mustNotAccept":["A zero-indexed version window.","A partial version range."],"proofSnippets":[{"id":"py-first-bad-version-init-bounds-chapter","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n"}]}},{"id":"loop-window","title":"Loop while multiple candidates remain","description":"Continue the search until the version window collapses to one candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"maintains_search_window","scope":"while-condition","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using a loop that can skip the remaining candidate","Looping over every version"],"hint":"For a first-true boundary search, `while left < right` keeps one candidate at exit.","semanticSpec":{"intent":"Maintain a narrowing search window over version numbers.","doneWhen":"The loop condition compares the active search bounds.","shouldFailWhen":"This step should fail if the loop ignores the search bounds or scans linearly.","roles":["search window","loop guard"],"mustProve":["The loop is controlled by the two boundary variables."],"mustNotAccept":["A fixed-count loop over versions.","A loop that does not use both bounds."],"proofSnippets":[{"id":"py-first-bad-version-loop-window-chapter","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n\n        while left < right:\n            pass"}]}},{"id":"calculate-mid","title":"Probe the midpoint version","description":"Compute a midpoint from the current version bounds each iteration.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"computes_midpoint_from_bounds","scope":"calculate-mid","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using normal division instead of integer division","Computing mid from the original n every time"],"hint":"Use `left + (right - left) // 2` or an equivalent integer midpoint.","semanticSpec":{"intent":"Derive the midpoint version from the current search bounds.","doneWhen":"Each loop iteration computes a midpoint that depends on both active bounds.","shouldFailWhen":"This step should fail if the midpoint is constant or only depends on one bound.","roles":["left boundary","right boundary","midpoint version"],"mustProve":["The midpoint is calculated inside the search loop.","The midpoint uses both bounds."],"mustNotAccept":["A fixed probe version.","Linear advancement by one version."],"proofSnippets":[{"id":"py-first-bad-version-calculate-mid-chapter","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n\n        while left < right:\n            mid = left + (right - left) // 2"}]}},{"id":"check-version","title":"Check the midpoint version","description":"Use the API predicate to decide whether the midpoint is already bad.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"branches_on_midpoint_boundary_predicate","scope":"check-boundary-predicate","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Checking `bad` directly instead of probing the midpoint","Calling the API on left or right instead of mid"],"hint":"The branch should ask whether `mid` is bad.","semanticSpec":{"intent":"Branch on a midpoint-derived boundary predicate.","doneWhen":"The code calls the bad-version predicate with the midpoint and branches on that result.","shouldFailWhen":"This step should fail if the predicate is not tied to the midpoint probe.","roles":["midpoint version","bad-version predicate"],"mustProve":["The predicate check uses the midpoint version.","The predicate branch controls the next bound update."],"mustNotAccept":["A branch that ignores the midpoint.","A direct return without an API check."],"proofSnippets":[{"id":"py-first-bad-version-check-version-chapter","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n\n        while left < right:\n            mid = left + (right - left) // 2\n            if isBadVersion(mid, bad):\n                pass"}]}},{"id":"narrow-window","title":"Keep the first bad candidate","description":"If mid is bad, keep it by moving right to mid; otherwise move left past mid.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"narrows_bounds_around_midpoint","scope":"adjust-direct-boundary","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using `right = mid - 1` and discarding a possible first bad version","Moving the wrong bound after a good midpoint"],"hint":"A bad midpoint might be the first bad version, so do not discard it.","semanticSpec":{"intent":"Narrow the direct-boundary search window without dropping the answer.","doneWhen":"Bad midpoint checks move the upper bound to mid, and good midpoint checks move the lower bound to mid + 1.","shouldFailWhen":"This step should fail if branch directions are reversed or if a bad midpoint is excluded.","roles":["predicate branch","lower boundary","upper boundary","midpoint version"],"mustProve":["The predicate branch controls both bound updates.","The true branch keeps mid as a candidate.","The false branch excludes mid by advancing left."],"mustNotAccept":["Discarding a bad midpoint with `right = mid - 1`.","Using `left = mid` after a good midpoint."],"proofSnippets":[{"id":"py-first-bad-version-narrow-window-chapter","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n\n        while left < right:\n            mid = left + (right - left) // 2\n            if isBadVersion(mid, bad):\n                right = mid\n            else:\n                left = mid + 1"}]}},{"id":"return-boundary","title":"Return the collapsed boundary","description":"Return the remaining version once the search window has collapsed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"returns_search_boundary","scope":"return-boundary","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Returning the last midpoint","Returning inside the loop before the boundary collapses"],"hint":"When the loop ends, left and right point to the first bad version.","semanticSpec":{"intent":"Return the final binary-search boundary.","doneWhen":"The function returns the collapsed search boundary after the loop.","shouldFailWhen":"This step should fail if the code returns a stale midpoint, API result, or constant.","roles":["collapsed boundary","first bad version"],"mustProve":["The return happens after boundary narrowing.","The returned value is the remaining search boundary."],"mustNotAccept":["Returning `mid` after the loop.","Returning a boolean API result."],"proofSnippets":[{"id":"py-first-bad-version-return-boundary-chapter","language":"python","code":"class Solution:\n    def isBadVersion(self, version: int, bad: int) -> bool:\n        return version >= bad\n\n    def firstBadVersion(self, n: int, bad: int) -> int:\n        left, right = 1, n\n        while left < right:\n            mid = left + (right - left) // 2\n            if isBadVersion(mid, bad):\n                right = mid\n            else:\n                left = mid + 1\n        return left"}]}}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Keep a window of possible first-bad versions, probe the middle, send a good probe later and let a bad probe keep itself.","workspacePanel":"code","body":["This is binary search on a yes/no answer instead of an exact match: the API flips from false to true exactly once, and the search hunts that flip.","The whole correctness rests on one move: a bad version stays a candidate until something earlier proves bad, so right lands on mid, never mid minus one."],"takeaways":[{"title":"The window holds only possible answers","body":"left and right bound the versions that could still be the first bad one; everything outside has been proven good or proven too late."},{"title":"A bad probe keeps itself","body":"right = mid, not mid - 1, because the bad midpoint is the earliest version known to be bad and might be the answer."},{"title":"Halve the API calls","body":"Each probe deletes half the remaining versions, so a range of two billion is settled in about 31 API calls instead of two billion."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
