{"id":"find-minimum-in-rotated-sorted-array","title":"Find Minimum in Rotated Sorted Array","difficulty":"medium","patterns":["binary-search"],"primaryConcept":"binary-search-modified","concepts":["binary-search-modified"],"problemForm":"core","companies":[],"category":"searching-sorting","compareMode":"exact","description":"You are given a sorted array of distinct integers that has been rotated between 1 and `n` times. Return the minimum element in the array.\n\nRequirements:\n- The array contains distinct values.\n- The original array was sorted in ascending order before rotation.\n- Return the minimum value, not its index.\n- Your solution should run in O(log n) time.","requiredComplexity":[{"metric":"time","bound":"O(log n)","scope":"function","functions":["findMin"],"case":"worst","enforcement":"hard","reason":"The prompt requires O(log n) time."}],"examples":[{"input":"nums = [4,5,6,7,0,1,2]","output":"0","explanation":"The sorted array was rotated so 0 is the pivot and the smallest value."},{"input":"nums = [3,4,5,1,2]","output":"1","explanation":"The minimum is the first value after the rotation break."},{"input":"nums = [11,13,15,17]","output":"11","explanation":"The array is still sorted without a visible break, so the first element is minimum."}],"constraints":[{"id":"1-len-nums-5000","text":"1 <= len(nums) <= 5000","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":5000}},{"id":"5000-nums-i-5000","text":"-5000 <= nums[i] <= 5000","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-5000,"max":5000}},{"id":"all-values-in-nums-are-distinct","text":"All values in nums are distinct.","check":{"kind":"uniqueness","target":"nums","selector":"items"}},{"id":"nums-is-a-rotated-ascending-sorted-array","text":"nums is a rotated ascending sorted array."}],"starterCode":"class Solution:\n    def findMin(self, nums: list[int]) -> int:\n        # Your code here\n        pass","functionName":"findMin","testCases":[{"id":"1","input":{"nums":[4,5,6,7,0,1,2]},"expected":0,"description":"Rotation point in the middle."},{"id":"2","input":{"nums":[3,4,5,1,2]},"expected":1,"description":"Small rotated array."},{"id":"3","input":{"nums":[11,13,15,17]},"expected":11,"description":"No visible rotation break."},{"id":"4","input":{"nums":[2,1]},"expected":1,"description":"Two elements rotated once."},{"id":"5","input":{"nums":[1]},"expected":1,"description":"Single-element array."},{"id":"h1","input":{"nums":[6,7,8,1,2,3,4,5]},"expected":1,"description":"The minimum sits just after a long rotated prefix."},{"id":"h2","input":{"nums":[30,40,50,60,10,20]},"expected":10,"description":"A larger rotation still finds the smallest value in O(log n) style splits."},{"id":"h3","input":{"nums":[5,1,2,3,4]},"expected":1,"description":"The rotation break appears immediately after the first element."},{"id":"h4","input":{"nums":[1,2,3,4]},"expected":1,"description":"Already sorted input remains unchanged."},{"id":"h5","input":{"nums":[4,5,6,7,8,1,2,3]},"expected":1,"description":"Another rotation point with a longer tail."},{"id":"topup-1","input":{"nums":[2,3,4,5,6,7,1]},"expected":1,"description":"Top-up case 1: the minimum can sit at the final index after a one-step rotation."},{"id":"topup-2","input":{"nums":[-1,0,2,4,-9,-7,-3]},"expected":-9,"description":"Top-up case 2: rotated sorted arrays may include negative values around the break."}],"hints":[{"level":1,"content":"Compare the middle value with the rightmost value. Which side must contain the rotation break?","revealPattern":false},{"level":2,"content":"If `nums[mid] > nums[right]`, the minimum must be to the right of `mid`. Otherwise, it is at `mid` or to the left.","revealPattern":true},{"level":3,"content":"Use `while left < right`; move `left = mid + 1` when mid is in the larger left half, otherwise move `right = mid`.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"mid-vs-left","name":"Compare midpoint with left boundary","summary":"Keep left and right bounds, then use nums[mid] compared with nums[left] to reason about which side is sorted.","decisionReason":"Comparing the midpoint to the left end is ambiguous on a rotated array: a midpoint above the left value can sit on either side of the break.","complexity":{"time":"O(log n)","space":"O(1)"},"tradeoffs":["Maintains left, mid, and right bounds.","Runs in O(log n) time and uses O(1) space.","The tradeoff is extra case reasoning when the left side looks sorted."],"isOptimal":false},{"id":"candidate-answer","name":"Keep a saved minimum candidate","summary":"Keep search bounds plus a best value seen whenever a sorted side reveals a possible minimum.","decisionReason":"Saving a running minimum while halving returns the same rotated-array minimum. This flow compares mid with nums[right] so the surviving side is visible without an extra candidate variable.","complexity":{"time":"O(log n)","space":"O(1)"},"tradeoffs":["Maintains left, right, and a saved candidate minimum.","Runs in O(log n) time and uses O(1) space.","The tradeoff is more state to update correctly after each comparison."],"isViable":true,"isOptimal":false},{"id":"binary-search","name":"Boundary-guided binary search","summary":"Use mid vs right to decide whether the minimum is right of mid or at/left of mid.","decisionReason":"Compare the midpoint to the right end to learn which side of the break the minimum sits on, discarding half each step in log time.","complexity":{"time":"O(log n)","space":"O(1)"},"tradeoffs":["Maintains only left, mid, and right bounds.","Runs in O(log n) time and uses O(1) space.","The tradeoff is that the boundary update must keep mid when nums[mid] could still be the minimum."],"isOptimal":true}]},"codingCheckpoints":[{"id":"bounds","title":"Initialize search bounds","description":"Set left and right to cover the entire array.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"initializes_search_bounds","scope":"init-pointers","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using a past-the-end upper bound","Forgetting that right should be a valid index"],"hint":"Start with the first and last valid indices as the search bounds.","semanticSpec":{"intent":"Initialize closed search bounds over the whole rotated array.","doneWhen":"This step is done when left starts at 0 and right starts at the last valid index.","shouldFailWhen":"This step should fail if the search begins with invalid or collapsed bounds.","roles":["left bound","right bound","rotated array"],"mustProve":["The lower bound starts at the first index.","The upper bound starts at the last valid index."],"mustNotAccept":["Using a past-the-end upper bound with closed-interval updates.","Skipping explicit bounds and scanning linearly."],"equivalentVariants":["Use the first valid index as the lower bound and the last valid index as the upper bound."],"proofSnippets":[{"id":"py-rotated-min-bounds","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    return nums[left]"}]}},{"id":"loop-condition","title":"Loop until bounds meet","description":"Continue while left < right so the final index is the minimum candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"maintains_search_window","scope":"while-loop","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using <= and risking an infinite loop","Returning before the bounds converge"],"hint":"The answer is found when left and right point to the same index.","semanticSpec":{"intent":"Maintain the strict search loop until both bounds identify one minimum candidate.","doneWhen":"This step is done when the loop continues while left < right and exits only after the candidate window converges.","shouldFailWhen":"This step should fail if the loop can skip convergence or uses a linear scan instead of a bounded search window.","roles":["search window","left bound","right bound"],"mustProve":["The loop condition is tied to left/right convergence."],"mustNotAccept":["Using <= and risking an infinite loop","Returning before the bounds converge"],"equivalentVariants":["Use while left < right with closed bounds."],"proofSnippets":[{"id":"py-rotated-min-loop","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    while left < right:\n        return nums[left]\n    return nums[left]"}]}},{"id":"calculate-mid","title":"Calculate the midpoint","description":"Compute mid from the current left and right bounds.","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 only one bound to compute mid","Computing mid from stale or constant bounds"],"hint":"Use both active bounds so each iteration probes the middle of the remaining window.","semanticSpec":{"intent":"Compute a midpoint from the active search bounds.","doneWhen":"This step is done when mid is derived from left and right inside the search loop.","shouldFailWhen":"This step should fail if mid is not tied to both current bounds.","roles":["left bound","right bound","midpoint"],"mustProve":["The midpoint is computed from both active bounds."],"mustNotAccept":["Computing mid from only left or only right.","Using a constant midpoint."],"equivalentVariants":["Use floor division or an overflow-safe equivalent of left + (right - left) // 2."],"proofSnippets":[{"id":"py-rotated-min-calculate-mid","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    while left < right:\n        mid = (left + right) // 2\n        return nums[mid]\n    return nums[left]"}]}},{"id":"mid-comparison","title":"Compare mid with right boundary","description":"Use nums[mid] > nums[right] to detect that mid is in the larger left portion.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"branches_on_rotated_ordering","scope":"check-sorted-half","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Comparing mid to left and losing the invariant","Ignoring the right boundary signal"],"hint":"The rightmost value tells whether the right half is sorted around the minimum.","semanticSpec":{"intent":"Compare the midpoint value with the right boundary to detect which side contains the rotation minimum.","doneWhen":"This step is done when nums[mid] is compared to nums[right] and that ordering decides the branch.","shouldFailWhen":"This step should fail if the branch ignores the rotated sorted boundary relationship.","roles":["midpoint","right boundary","rotated ordering"],"mustProve":["The code probes nums[mid].","The code compares the midpoint value with a boundary value from the active window."],"mustNotAccept":["Comparing mid only to a target that does not exist.","Scanning for adjacent drops linearly."],"equivalentVariants":["Use nums[mid] > nums[right] or the equivalent reversed comparison."],"proofSnippets":[{"id":"py-rotated-min-mid-comparison","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    while left < right:\n        mid = (left + right) // 2\n        if nums[mid] > nums[right]:\n            return nums[right]\n        return nums[mid]\n    return nums[left]"}]}},{"id":"move-bounds","title":"Move the correct boundary","description":"Move left to mid + 1 when the minimum is right of mid; otherwise keep mid by setting right = mid.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"narrows_bounds_around_midpoint","scope":"adjust-rotated-boundary","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using right = mid - 1 and skipping a possible minimum","Using left = mid and getting stuck"],"hint":"When mid could be the minimum, keep it in the search range.","semanticSpec":{"intent":"Move left to mid + 1 when the minimum is right of mid; otherwise keep mid by setting right = mid.","doneWhen":"Move left to mid + 1 when the minimum is right of mid; otherwise keep mid by setting right = mid.","roles":["left bound","right bound","midpoint","rotated ordering"],"mustProve":["Move left to mid + 1 when the minimum is right of mid; otherwise keep mid by setting right = mid."],"mustNotAccept":["Using right = mid - 1 and skipping a possible minimum","Using left = mid and getting stuck"],"proofSnippets":[{"id":"py-rotated-min-move-bounds","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    while left < right:\n        mid = (left + right) // 2\n        if nums[mid] > nums[right]:\n            left = mid + 1\n        else:\n            right = mid\n    return 0"}]}},{"id":"return-min","title":"Return nums[left]","description":"Return the value at the converged boundary.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"returns_search_boundary_value","scope":"return-min","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Returning the index instead of the value","Returning nums[mid] after the loop"],"hint":"After convergence, left and right identify the minimum position.","semanticSpec":{"intent":"Return the value at the converged boundary.","doneWhen":"Return the value at the converged boundary.","roles":["converged boundary","minimum value","terminal return"],"mustProve":["Return the value at the converged boundary."],"mustNotAccept":["Returning the index instead of the value","Returning nums[mid] after the loop"],"proofSnippets":[{"id":"py-rotated-min-return","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    while left < right:\n        mid = (left + right) // 2\n        if nums[mid] > nums[right]:\n            left = mid + 1\n        else:\n            right = mid\n    return nums[left]"}]}}],"version":2,"slides":[{"id":"read-the-signal","chapter":"The array","kind":"info","eyebrow":"Read the problem","title":"Find the smallest in a rotated list","workspacePanel":"problem","body":["You get an ascending sorted list rotated at an unknown point. Return its smallest value.","A scan would walk all n values to reach it. The list keeps most of its order through the rotation, and the question is whether that order can be used to skip work."]},{"id":"the-break","chapter":"The idea","kind":"info","eyebrow":"See the shape","title":"The minimum is the one place order breaks","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"break-intro","state":{"nums":[4,5,6,7,0,1,2],"left":0,"right":6,"mid":3}}]},"body":["Everywhere except one spot, each value is larger than the one before. The single exception is the rotation, where a large value is followed by the smallest one.","So finding the minimum means finding that drop. The trick is deciding, from a midpoint, which side the drop lies on.","From one midpoint, we need a reference value that tells which side still holds the drop."]},{"id":"which-half","chapter":"The idea","kind":"case-probe","eyebrow":"Read the signal","title":"If the midpoint value is larger than the right end, where is the minimum?","summary":"nums[mid] = 7 and nums[right] = 2.","workspacePanel":"visualizer","options":[{"id":"right-half","label":"Somewhere to the right of the midpoint","rationale":"If the midpoint were in the same sorted run as the right end, it would be smaller. Being larger means the drop, and so the minimum, lies past the midpoint.","isCorrect":true},{"id":"left-half","label":"In the left half, at or before the midpoint","rationale":"The left half from the start to the midpoint is rising here; its smallest is the start, which is still above the right end. The drop is to the right.","isCorrect":false},{"id":"at-mid","label":"Exactly at the midpoint","rationale":"The midpoint is larger than the right end, so it cannot be the minimum. The smaller values lie beyond it.","isCorrect":false}],"answer":"To the right. A midpoint above the right end cannot share its sorted run, so the drop, and the minimum, lies past the midpoint. Move the low bound to mid + 1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"which-half-state","state":{"nums":[4,5,6,7,0,1,2],"left":0,"right":6,"mid":3}}]}},{"id":"other-case","chapter":"The idea","kind":"case-probe","eyebrow":"Read the signal","title":"If the midpoint value is at or below the right end, what does that mean for it?","summary":"The active window is [0, 1, 2], with mid on 1 and right on 2.","workspacePanel":"visualizer","options":[{"id":"mid-or-left","label":"The minimum is at the midpoint or to its left, so the midpoint stays a candidate","rationale":"The midpoint is part of the run ending at the right, so the drop is on its left, or the midpoint itself is the smallest. Either way it must not be discarded.","isCorrect":true},{"id":"right-half","label":"The minimum is to the right","rationale":"That is the other case. A midpoint at or below the right end means the right portion is already in order, so the minimum is not beyond it.","isCorrect":false},{"id":"drop-mid","label":"The midpoint is ruled out","rationale":"The midpoint could be the minimum itself. The high bound moves to the midpoint, keeping it, rather than past it.","isCorrect":false}],"answer":"The minimum is at the midpoint or to its left, so the midpoint is still a candidate. Move the high bound to the midpoint, never past it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"other-case-state","state":{"nums":[4,5,6,7,0,1,2],"left":4,"right":6,"mid":5}}]}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"nums":[4,5,6,7,0,1,2],"left":0,"right":6,"mid":3}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Halve toward the drop","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[4,5,6,7,0,1,2],"left":0,"right":6,"mid":3}}]},"body":["left and right bound where the minimum could be. Each step takes the midpoint and compares it to the value at right.","If the midpoint is larger, the drop is past it, so left moves to mid + 1. Otherwise the midpoint stays in range and right moves to mid.","The bounds close until they meet, and that meeting point is the minimum."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the search","title":"Trace the closing bounds","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first","state":{"nums":[4,5,6,7,0,1,2],"left":0,"right":6,"mid":3}},{"id":"second","state":{"nums":[4,5,6,7,0,1,2],"left":4,"right":6,"mid":5}},{"id":"converge","state":{"nums":[4,5,6,7,0,1,2],"left":4,"right":4,"mid":4}}]},"beats":[{"id":"first","title":"Midpoint is 7, right end is 2. Which way?","summary":"The bounds span the whole array; the midpoint lands on 7.","prompt":"The midpoint value 7 is larger than the right end 2.","options":[{"id":"go-right","label":"Move left to mid + 1","rationale":"7 above 2 means the drop is past the midpoint, so the minimum is to the right. left jumps to index 4.","isCorrect":true},{"id":"go-left","label":"Move right to the midpoint","rationale":"That is the other case, for a midpoint at or below the right end. Here 7 is larger, so the minimum is to the right.","isCorrect":false},{"id":"done","label":"Return 7","rationale":"7 is larger than values still ahead, so it cannot be the minimum. The search continues rightward.","isCorrect":false}],"answer":"Move left to mid + 1. 7 is above the right end, so the minimum is past the midpoint; left becomes index 4."},{"id":"second","title":"Now the midpoint is 1, right end is 2. Which way?","summary":"The window has three values left.","prompt":"nums[mid] = 1 and nums[right] = 2.","options":[{"id":"go-left","label":"Move right to the midpoint","rationale":"1 is at or below the right end, so the minimum is at the midpoint or to its left. right moves to the midpoint, keeping it in range.","isCorrect":true},{"id":"go-right","label":"Move left to mid + 1","rationale":"That would discard the midpoint, but a midpoint below the right end might be the minimum. right moves to it instead.","isCorrect":false},{"id":"return-one","label":"Return 1","rationale":"There is still a smaller value, 0, to the left. The search keeps the midpoint but does not stop yet.","isCorrect":false}],"answer":"Move right to the midpoint. 1 is at or below the right end, so the minimum is at or before it; right comes in to keep it."},{"id":"converge","title":"The bounds meet on a single cell. What is returned?","summary":"left and right have closed onto index 4.","prompt":"The window has narrowed to one value.","options":[{"id":"zero","label":"0, the value where they meet","rationale":"The bounds met at the drop. The single remaining value, 0, is the minimum.","isCorrect":true},{"id":"one","label":"1","rationale":"1 was kept in range but the bounds closed past it onto the smaller 0. The meeting point holds the minimum.","isCorrect":false},{"id":"keep-going","label":"Keep halving","rationale":"Once left and right meet, the window is a single cell and the search ends. That cell is the answer.","isCorrect":false}],"answer":"0. The bounds met at index 4, and that value is the minimum."}]},{"id":"discard-mid-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"When narrowing left, can you move right to mid - 1?","summary":"Stepping the high bound to mid - 1 is the usual binary-search move and feels tidy, shrinking the window by one more cell each time. It looks like the same search, just a touch faster. Watch it run on a list where the midpoint lands on the answer.","workspacePanel":"trace","pitfall":"The search below moves the high bound to mid - 1 instead of mid when narrowing left.","whyItMatters":"When the midpoint is at or below the right end, the midpoint might be the minimum, so it has to stay in range. Move the high bound to mid, not mid - 1, or the answer can be discarded.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"left = 0\nright = len(nums) - 1\nwhile left < right:\n    mid = (left + right) // 2\n    if nums[mid] > nums[right]:\n        left = mid + 1\n    else:\n        right = mid - 1\nreturn nums[left]","steps":[{"id":"mid-is-min","title":"The midpoint lands on the minimum","codeLine":5,"summary":"nums = [3, 1, 2]. The midpoint is index 1, value 1, the true minimum. It is not larger than the right end 2.","state":{"nums":[3,1,2],"left":0,"right":2,"mid":1}},{"id":"discards-it","title":"mid - 1 throws the minimum away","codeLine":8,"summary":"Taking the else branch, the high bound moves to mid - 1, index 0. The minimum at index 1 is now outside the window.","state":{"nums":[3,1,2],"left":0,"right":0,"mid":1}},{"id":"wrong-answer","title":"It returns 3","codeLine":9,"summary":"left and right have collapsed onto index 0, value 3. The search returns 3, the largest value, instead of the minimum 1.","state":{"nums":[3,1,2],"left":0,"right":0,"mid":0}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let left = 0;\nlet right = nums.length - 1;\nwhile (left < right) {\n    const mid = Math.floor((left + right) / 2);\n    if (nums[mid] > nums[right]) {\n        left = mid + 1;\n    } else {\n        right = mid - 1;\n    }\n}\nreturn nums[left];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11},"statementBundles":{"8":{"startLine":8,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let left = 0;\nlet right = nums.length - 1;\nwhile (left < right) {\n    const mid = Math.floor((left + right) / 2);\n    if (nums[mid] > nums[right]) {\n        left = mid + 1;\n    } else {\n        right = mid - 1;\n    }\n}\nreturn nums[left];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11},"statementBundles":{"8":{"startLine":8,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int left = 0;\nint right = nums.size() - 1;\nwhile (left < right) {\n    int mid = Math.floorDiv((left + right), 2);\n    if (nums.get(mid) > nums.get(right)) {\n        left = mid + 1;\n    } else {\n        right = mid - 1;\n    }\n}\nreturn nums.get(left);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11},"statementBundles":{"8":{"startLine":8,"endLine":10}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int left = 0;\nint right = nums.Count - 1;\nwhile (left < right) {\n    int mid = (left + right) / 2;\n    if (nums[mid] > nums[right]) {\n        left = mid + 1;\n    } else {\n        right = mid - 1;\n    }\n}\nreturn nums[left];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11},"statementBundles":{"8":{"startLine":8,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int left = 0;\nint right = nums.size() - 1;\nwhile (left < right) {\n    int mid = (left + right) / 2;\n    if (nums[mid] > nums[right]) {\n        left = mid + 1;\n    } else {\n        right = mid - 1;\n    }\n}\nreturn nums[left];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11},"statementBundles":{"8":{"startLine":8,"endLine":10}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Comparing the midpoint to the right end and discarding the larger side drove the search straight to the minimum.","Time to stress that rule. What if the array was never rotated, so it is already sorted, and what about the smallest case, a list of just two elements?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[4,5,6,7,0,1,2],"left":0,"right":6,"mid":3}}]}},{"id":"not-rotated-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if the list was not rotated at all?","summary":"nums = [1, 2, 3, 4, 5], already sorted.","workspacePanel":"visualizer","options":[{"id":"first","label":"1, the first element","rationale":"Every midpoint is at or below the right end, so right keeps coming in and the bounds collapse onto index 0, the true minimum.","isCorrect":true},{"id":"invalid","label":"There is no rotation to find","rationale":"A non-rotated array is just rotation by zero. The same comparison still drives the bounds to the smallest value at the front.","isCorrect":false},{"id":"last","label":"5, the right end","rationale":"The minimum of a sorted array is at the front. The search lands on the first element.","isCorrect":false}],"answer":"1. With no rotation every midpoint sits below the right end, so the high bound keeps closing left until the bounds meet at index 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"not-rotated-state","state":{"nums":[1,2,3,4,5],"left":0,"right":2,"mid":1}}]}},{"id":"two-elements-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What about a list of two?","summary":"nums = [2, 1].","workspacePanel":"visualizer","options":[{"id":"one","label":"1, the second element","rationale":"The midpoint is 2 (index 0), above the right end 1, so the minimum is to the right. left moves to index 1, where the bounds meet on 1.","isCorrect":true},{"id":"two","label":"2, the first element","rationale":"2 is larger than the right end, so it cannot be the minimum. The search moves right to the 1.","isCorrect":false},{"id":"loop","label":"It loops on two elements","rationale":"The window strictly shrinks: comparing the midpoint to the right end moves a bound and the two close onto 1.","isCorrect":false}],"answer":"1. The midpoint 2 exceeds the right end, so the minimum is to the right, and the bounds meet on 1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-elements-edge-state","state":{"nums":[2,1],"left":0,"right":1,"mid":0}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Compare to the right end, and close in","summary":"A midpoint at or below the right end might be the minimum, so keep it.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-start","state":{"nums":[4,5,6,7,0,1,2],"left":0,"right":6,"mid":3}}]},"body":["Bound the array with left and right. Each step compare the midpoint to the value at the right end, keep the side the drop is on, and never move the high bound past the midpoint."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the rotated-minimum search","eyebrow":"Code the rule","summary":"Comparing the midpoint to the right end picks the side that holds the drop. Now build it: set left and right over the whole array, loop while left is below right, compare nums[mid] to nums[right], move left past mid when mid is larger and pull right in to mid otherwise, then return the value where they meet.","workspacePanel":"code","checkpoints":[{"id":"bounds","title":"Initialize search bounds","description":"Set left and right to cover the entire array.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"initializes_search_bounds","scope":"init-pointers","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using a past-the-end upper bound","Forgetting that right should be a valid index"],"hint":"Start with the first and last valid indices as the search bounds.","semanticSpec":{"intent":"Initialize closed search bounds over the whole rotated array.","doneWhen":"This step is done when left starts at 0 and right starts at the last valid index.","shouldFailWhen":"This step should fail if the search begins with invalid or collapsed bounds.","roles":["left bound","right bound","rotated array"],"mustProve":["The lower bound starts at the first index.","The upper bound starts at the last valid index."],"mustNotAccept":["Using a past-the-end upper bound with closed-interval updates.","Skipping explicit bounds and scanning linearly."],"equivalentVariants":["Use the first valid index as the lower bound and the last valid index as the upper bound."],"proofSnippets":[{"id":"py-rotated-min-bounds","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    return nums[left]"}]}},{"id":"loop-condition","title":"Loop until bounds meet","description":"Continue while left < right so the final index is the minimum candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"maintains_search_window","scope":"while-loop","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using <= and risking an infinite loop","Returning before the bounds converge"],"hint":"The answer is found when left and right point to the same index.","semanticSpec":{"intent":"Maintain the strict search loop until both bounds identify one minimum candidate.","doneWhen":"This step is done when the loop continues while left < right and exits only after the candidate window converges.","shouldFailWhen":"This step should fail if the loop can skip convergence or uses a linear scan instead of a bounded search window.","roles":["search window","left bound","right bound"],"mustProve":["The loop condition is tied to left/right convergence."],"mustNotAccept":["Using <= and risking an infinite loop","Returning before the bounds converge"],"equivalentVariants":["Use while left < right with closed bounds."],"proofSnippets":[{"id":"py-rotated-min-loop","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    while left < right:\n        return nums[left]\n    return nums[left]"}]}},{"id":"calculate-mid","title":"Calculate the midpoint","description":"Compute mid from the current left and right bounds.","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 only one bound to compute mid","Computing mid from stale or constant bounds"],"hint":"Use both active bounds so each iteration probes the middle of the remaining window.","semanticSpec":{"intent":"Compute a midpoint from the active search bounds.","doneWhen":"This step is done when mid is derived from left and right inside the search loop.","shouldFailWhen":"This step should fail if mid is not tied to both current bounds.","roles":["left bound","right bound","midpoint"],"mustProve":["The midpoint is computed from both active bounds."],"mustNotAccept":["Computing mid from only left or only right.","Using a constant midpoint."],"equivalentVariants":["Use floor division or an overflow-safe equivalent of left + (right - left) // 2."],"proofSnippets":[{"id":"py-rotated-min-calculate-mid","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    while left < right:\n        mid = (left + right) // 2\n        return nums[mid]\n    return nums[left]"}]}},{"id":"mid-comparison","title":"Compare mid with right boundary","description":"Use nums[mid] > nums[right] to detect that mid is in the larger left portion.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"branches_on_rotated_ordering","scope":"check-sorted-half","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Comparing mid to left and losing the invariant","Ignoring the right boundary signal"],"hint":"The rightmost value tells whether the right half is sorted around the minimum.","semanticSpec":{"intent":"Compare the midpoint value with the right boundary to detect which side contains the rotation minimum.","doneWhen":"This step is done when nums[mid] is compared to nums[right] and that ordering decides the branch.","shouldFailWhen":"This step should fail if the branch ignores the rotated sorted boundary relationship.","roles":["midpoint","right boundary","rotated ordering"],"mustProve":["The code probes nums[mid].","The code compares the midpoint value with a boundary value from the active window."],"mustNotAccept":["Comparing mid only to a target that does not exist.","Scanning for adjacent drops linearly."],"equivalentVariants":["Use nums[mid] > nums[right] or the equivalent reversed comparison."],"proofSnippets":[{"id":"py-rotated-min-mid-comparison","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    while left < right:\n        mid = (left + right) // 2\n        if nums[mid] > nums[right]:\n            return nums[right]\n        return nums[mid]\n    return nums[left]"}]}},{"id":"move-bounds","title":"Move the correct boundary","description":"Move left to mid + 1 when the minimum is right of mid; otherwise keep mid by setting right = mid.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"narrows_bounds_around_midpoint","scope":"adjust-rotated-boundary","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Using right = mid - 1 and skipping a possible minimum","Using left = mid and getting stuck"],"hint":"When mid could be the minimum, keep it in the search range.","semanticSpec":{"intent":"Move left to mid + 1 when the minimum is right of mid; otherwise keep mid by setting right = mid.","doneWhen":"Move left to mid + 1 when the minimum is right of mid; otherwise keep mid by setting right = mid.","roles":["left bound","right bound","midpoint","rotated ordering"],"mustProve":["Move left to mid + 1 when the minimum is right of mid; otherwise keep mid by setting right = mid."],"mustNotAccept":["Using right = mid - 1 and skipping a possible minimum","Using left = mid and getting stuck"],"proofSnippets":[{"id":"py-rotated-min-move-bounds","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    while left < right:\n        mid = (left + right) // 2\n        if nums[mid] > nums[right]:\n            left = mid + 1\n        else:\n            right = mid\n    return 0"}]}},{"id":"return-min","title":"Return nums[left]","description":"Return the value at the converged boundary.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"returns_search_boundary_value","scope":"return-min","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Returning the index instead of the value","Returning nums[mid] after the loop"],"hint":"After convergence, left and right identify the minimum position.","semanticSpec":{"intent":"Return the value at the converged boundary.","doneWhen":"Return the value at the converged boundary.","roles":["converged boundary","minimum value","terminal return"],"mustProve":["Return the value at the converged boundary."],"mustNotAccept":["Returning the index instead of the value","Returning nums[mid] after the loop"],"proofSnippets":[{"id":"py-rotated-min-return","language":"python","code":"def findMin(nums: list[int]) -> int:\n    left, right = 0, len(nums) - 1\n    while left < right:\n        mid = (left + right) // 2\n        if nums[mid] > nums[right]:\n            left = mid + 1\n        else:\n            right = mid\n    return nums[left]"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Compare the midpoint to the right end; the smaller side hides the minimum.","workspacePanel":"code","body":["A rotated sorted array has one drop point, and that drop is the minimum. The midpoint’s relation to the right end says which half holds it.","If the midpoint is larger than the right end, the drop is to its right; otherwise it is at the midpoint or to its left."],"takeaways":[{"title":"The right end is the reference","body":"Comparing nums[mid] to nums[right] is what survives rotation; comparing to nums[left] cannot tell a rotated half from a sorted one."},{"title":"Never step over the midpoint","body":"When the midpoint could be the minimum you move right to mid, not mid - 1, so the smallest value is never skipped."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"length","constraints":["distinct"],"valueRange":{"min":-5000,"max":5000}},"executionStyle":"solution-method"}
