{"id":"search-insert-position","title":"Search Insert Position","difficulty":"easy","patterns":["binary-search"],"primaryConcept":"binary-search-basics","concepts":["binary-search-basics"],"problemForm":"intro","companies":[],"category":"searching-sorting","compareMode":"exact","description":"Given a sorted array of distinct integers `nums` and an integer `target`, return the index if `target` is found. If it is not found, return the index where it would be inserted to keep `nums` sorted.\n\nRequirements:\n- `nums` is sorted in ascending order.\n- Return an index from 0 to `len(nums)`.\n- Your solution should run in O(log n) time.","requiredComplexity":[{"metric":"time","bound":"O(log n)","scope":"function","functions":["searchInsert"],"case":"worst","enforcement":"hard","reason":"The prompt requires O(log n) time."}],"examples":[{"input":"nums = [1,3,5,6], target = 5","output":"2","explanation":"Target 5 already appears at index 2."},{"input":"nums = [1,3,5,6], target = 2","output":"1","explanation":"2 should be inserted before 3 to keep the array sorted."},{"input":"nums = [1,3,5,6], target = 7","output":"4","explanation":"7 belongs after the last element, at index len(nums)."}],"constraints":[{"id":"1-len-nums-10-4","text":"1 <= len(nums) <= 10^4","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":10000}},{"id":"10-4-nums-i-10-4","text":"-10^4 <= nums[i] <= 10^4"},{"id":"nums-contains-distinct-values-sorted-in-ascending-order","text":"nums contains distinct values sorted in ascending order."},{"id":"10-4-target-10-4","text":"-10^4 <= target <= 10^4"}],"starterCode":"class Solution:\n    def searchInsert(self, nums: list[int], target: int) -> int:\n        # Your code here\n        pass","functionName":"searchInsert","testCases":[{"id":"1","input":{"nums":[1,3,5,6],"target":5},"expected":2,"description":"Target exists."},{"id":"2","input":{"nums":[1,3,5,6],"target":2},"expected":1,"description":"Insert in the middle."},{"id":"3","input":{"nums":[1,3,5,6],"target":7},"expected":4,"description":"Insert after the end."},{"id":"4","input":{"nums":[1,3,5,6],"target":0},"expected":0,"description":"Insert before the beginning."},{"id":"5","input":{"nums":[-10,0,5,10],"target":0},"expected":1,"description":"Works with negative values."},{"id":"h1","input":{"nums":[-5],"target":-6},"expected":0,"description":"A target below a single negative value inserts at index 0."},{"id":"h2","input":{"nums":[1],"target":0},"expected":0,"description":"A target before a single element still inserts at the front."},{"id":"h3","input":{"nums":[1],"target":2},"expected":1,"description":"A target after a single element inserts at the end."},{"id":"h4","input":{"nums":[2,4,6,8],"target":5},"expected":2,"description":"Binary search should land between middle values."},{"id":"h5","input":{"nums":[1,3,5,7,9],"target":4},"expected":2,"description":"Insert between distinct sorted values."}],"hints":[{"level":1,"content":"If the target is missing, the final left boundary tells where it should be inserted.","revealPattern":false},{"level":2,"content":"Use binary search and keep narrowing toward the first position whose value is not less than target.","revealPattern":true},{"level":3,"content":"When the loop ends after `left > right`, return `left`; it is the insertion point.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"half-open-lower-bound","name":"Half-open lower-bound search","summary":"Keep a left-inclusive, right-exclusive range and narrow it until left is the first position where target can fit.","decisionReason":"Half-open lower-bound search returns the same insertion index in O(log n) time. The guided implementation uses closed bounds so left, right, and the surviving insertion slot map directly to the trace.","complexity":{"time":"O(log n)","space":"O(1)"},"tradeoffs":["Maintains left and right where right may equal nums length.","Runs in O(log n) time and uses O(1) space.","The tradeoff is no immediate equality return, but the range convention must stay precise."],"isViable":true,"isOptimal":false},{"id":"binary-search","name":"Binary search boundary","summary":"Search for the target, and return the left boundary when absent.","decisionReason":"This fits best for the walkthrough because the state is simple: return immediately when found, otherwise return the final left boundary.","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 handling equality as its own branch before using the final insertion boundary."],"isOptimal":true}]},"codingCheckpoints":[{"id":"bounds","title":"Initialize binary search bounds","description":"Set left and right to the first and last valid indices.","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 with a closed interval","Starting right at 0"],"hint":"Use a consistent closed interval.","semanticSpec":{"intent":"Initialize a closed binary-search window over the full sorted array.","doneWhen":"This step is done when left starts at the first index and right starts at the last valid index before the search loop.","shouldFailWhen":"This step should fail if either bound is missing, if right is initialized inconsistently for a closed interval, or if the search starts from a partial range.","roles":["left bound","right bound","sorted input array","closed search window"],"mustProve":["The lower bound is initialized to the first searchable index.","The upper bound is initialized to the last searchable index.","The bounds are established before the loop that probes midpoints."],"mustNotAccept":["Starting both bounds at the same side.","Using a half-open right bound while the loop and updates are written as a closed interval.","Skipping explicit search bounds and scanning linearly."],"equivalentVariants":["Use the first valid index for the lower bound and the last valid index for the upper bound.","Use equivalent lower and upper search variables with the same closed-window meaning."],"proofSnippets":[{"id":"py-search-insert-bounds","language":"python","code":"def searchInsert(nums: list[int], target: int) -> int:\n    left, right = 0, len(nums) - 1\n    while left <= right:\n        return left\n    return left"}]}},{"id":"midpoint","title":"Compute midpoint each loop","description":"Compute mid from the current 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 a stale midpoint","Not updating mid after moving bounds"],"hint":"mid should reflect the current search interval.","semanticSpec":{"intent":"Compute each midpoint from the current binary-search bounds inside the search loop.","doneWhen":"This step is done when the loop derives `mid` from the current left/right bounds before probing `nums[mid]`.","shouldFailWhen":"This step should fail if the midpoint is stale, hard-coded, derived from unrelated values, or computed outside the narrowing loop only once.","roles":["left bound","right bound","midpoint","current search window"],"mustProve":["The midpoint is computed from the current lower and upper bounds.","The midpoint is recomputed as the search window changes."],"mustNotAccept":["Using a fixed midpoint.","Computing mid from array length alone after bounds have narrowed.","Linear scanning without a midpoint probe."],"equivalentVariants":["Use `(left + right) // 2`.","Use `left + (right - left) // 2` or an equivalent overflow-safe form."],"proofSnippets":[{"id":"py-search-insert-midpoint","language":"python","code":"def searchInsert(nums: list[int], target: int) -> int:\n    left, right = 0, len(nums) - 1\n    while left <= right:\n        mid = left + (right - left) // 2\n        if nums[mid] < target:\n            left = mid + 1\n        else:\n            right = mid - 1\n    return -1"}]}},{"id":"compare-target","title":"Return mid on exact hit","description":"Compare target to nums[mid] and return mid when they match.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"returns_search_hit","scope":"compare-and-return","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Skipping the equality case","Returning the target value instead of the index"],"hint":"When the midpoint value equals target, the answer is the midpoint index.","semanticSpec":{"intent":"Probe nums[mid] and return the midpoint index on an exact target hit.","doneWhen":"This step is done when the equality case returns `mid` after reading `nums[mid]`.","shouldFailWhen":"This step should fail if equality is ignored, the code returns a value other than mid on hit, or the midpoint probe compares against an unrelated value.","roles":["midpoint probe","target","exact-hit return"],"mustProve":["The code reads the array at the computed midpoint.","The target equality case returns the midpoint index."],"mustNotAccept":["Returning the target value instead of the index.","Skipping the exact hit case.","Comparing target against unrelated array positions."],"equivalentVariants":["Use `if nums[mid] == target: return mid`.","Use equivalent comparison ordering with the same hit-return behavior."],"proofSnippets":[{"id":"py-search-insert-compare","language":"python","code":"def searchInsert(nums: list[int], target: int) -> int:\n    left, right = 0, len(nums) - 1\n    while left <= right:\n        mid = left + (right - left) // 2\n        if nums[mid] == target:\n            return mid\n        return -1\n    return -1"}]}},{"id":"narrow-bounds","title":"Narrow bounds on a miss","description":"Move left after mid when nums[mid] is too small, otherwise move right before mid.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"narrows_bounds_around_midpoint","scope":"adjust-exact-hit-boundaries","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Moving a boundary to mid instead of past mid","Moving the wrong boundary for the comparison"],"hint":"After checking equality, discard the half that cannot contain target.","semanticSpec":{"intent":"Use the midpoint comparison to shrink the closed search window after a miss.","doneWhen":"This step is done when smaller midpoint values advance the lower bound past mid and larger midpoint values retreat the upper bound before mid.","shouldFailWhen":"This step should fail if a miss keeps mid in the window, moves the wrong boundary, or uses constants unrelated to the midpoint.","roles":["midpoint probe","target","lower bound update","upper bound update"],"mustProve":["The lower bound advances to one past mid when `nums[mid]` is smaller than target.","The upper bound retreats to one before mid when `nums[mid]` is greater than target."],"mustNotAccept":["Using `left = mid` or `right = mid` in a closed interval.","Moving left when the midpoint is too large.","Moving right when the midpoint is too small."],"equivalentVariants":["Use separate less-than and else branches after the equality return.","Use equivalent comparison ordering that still advances the correct closed-interval boundary past mid."],"proofSnippets":[{"id":"py-search-insert-narrow-bounds","language":"python","code":"def searchInsert(nums: list[int], target: int) -> int:\n    left, right = 0, len(nums) - 1\n    while left <= right:\n        mid = left + (right - left) // 2\n        if nums[mid] == target:\n            return mid\n        if nums[mid] < target:\n            left = mid + 1\n        else:\n            right = mid - 1\n    return -1"}]}},{"id":"return-left","title":"Return insertion boundary","description":"Return left after the loop when target is absent.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"returns_search_boundary","scope":"return-left","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Returning right","Returning -1 for missing target"],"hint":"left is the first position greater than target after the search.","semanticSpec":{"intent":"Return the final insertion boundary when the target is not found.","doneWhen":"This step is done when the function returns the lower boundary after the binary-search loop exits without an exact hit.","shouldFailWhen":"This step should fail if missing targets return -1, return the upper boundary, or return before both narrowing directions have been considered.","roles":["lower bound","upper bound","insertion index","missing-target return"],"mustProve":["Both lower and upper bound updates can occur around midpoint probes.","The final returned value is the boundary that points to the target insertion position.","The missing-target return happens after the search loop finishes."],"mustNotAccept":["Returning -1 for a missing target.","Returning `right` after the loop for a lower-bound insertion contract.","Returning inside the loop before the insertion point is determined."],"equivalentVariants":["Return `left` after a closed-interval binary search.","Use an equivalent lower-bound binary search that returns the first index whose value is not less than target."],"proofSnippets":[{"id":"py-search-insert-return-left","language":"python","code":"def searchInsert(nums: list[int], target: int) -> int:\n    left, right = 0, len(nums) - 1\n    while left <= right:\n        mid = left + (right - left) // 2\n        if nums[mid] == target:\n            return mid\n        if nums[mid] < target:\n            left = mid + 1\n        else:\n            right = mid - 1\n    return left"}]}}],"version":2,"slides":[{"id":"the-task","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Where does the target belong?","workspacePanel":"problem","body":["Sorted array, target value: return the target's index if it is present. If it is not present, return the index where it would be inserted to keep the order.","Either way the answer is a single index. The obvious way to find it is to walk the array until you hit a value that is not smaller than the target."]},{"id":"linear-scan","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Walk until a value is big enough","summary":"The trace below finds the insertion point by checking one index at a time.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"for i in range(len(nums)):\n    if nums[i] >= target:\n        return i\nreturn len(nums)","steps":[{"id":"scan-zero","title":"Index 0 is too small","codeLine":2,"summary":"nums = [1, 3, 5, 7], target = 9. nums[0] is 1, smaller than 9, so the scan steps forward.","state":{"nums":[1,3,5,7],"target":9,"i":0}},{"id":"scan-one","title":"Index 1 is too small","codeLine":2,"summary":"nums[1] is 3, still smaller than 9. The scan only ever advances one step at a time.","state":{"nums":[1,3,5,7],"target":9,"i":1}},{"id":"scan-two","title":"Index 2 is too small","codeLine":2,"summary":"nums[2] is 5, smaller than 9. Three checks in and nothing is big enough yet.","state":{"nums":[1,3,5,7],"target":9,"i":2}},{"id":"scan-three","title":"Index 3 is too small","codeLine":2,"summary":"nums[3] is 7, the last element, still smaller than 9. Every index was checked and none qualified.","state":{"nums":[1,3,5,7],"target":9,"i":3}},{"id":"scan-falls-off","title":"Fall off the end","codeLine":4,"summary":"No value was big enough, so the target belongs after everything: return len(nums) = 4. Four checks for four numbers.","state":{"nums":[1,3,5,7],"target":9,"i":4}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"for (let i = 0; i < nums.length; i++) {\n    if (nums[i] >= target) {\n        return i;\n    }\n}\nreturn nums.length;","lineMap":{"1":1,"2":2,"3":3,"4":6},"statementBundles":{"3":{"startLine":3,"endLine":5}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"for (let i = 0; i < nums.length; i++) {\n    if (nums[i] >= target) {\n        return i;\n    }\n}\nreturn nums.length;","lineMap":{"1":1,"2":2,"3":3,"4":6},"statementBundles":{"3":{"startLine":3,"endLine":5}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"for (int i = 0; i < nums.size(); i++) {\n    if (nums.get(i) >= target) {\n        return i;\n    }\n}\nreturn nums.size();","lineMap":{"1":1,"2":2,"3":3,"4":6},"statementBundles":{"3":{"startLine":3,"endLine":5}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"for (int i = 0; i < nums.Count; i++) {\n    if (nums[i] >= target) {\n        return i;\n    }\n}\nreturn nums.Count;","lineMap":{"1":1,"2":2,"3":3,"4":6},"statementBundles":{"3":{"startLine":3,"endLine":5}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"for (int i = 0; i < nums.size(); i++) {\n    if (nums[i] >= target) {\n        return i;\n    }\n}\nreturn nums.size();","lineMap":{"1":1,"2":2,"3":3,"4":6},"statementBundles":{"3":{"startLine":3,"endLine":5}}}}},"body":["One pass: step through the array and return the first index whose value is not smaller than the target. If nothing qualifies, the target belongs at the end."]},{"id":"scan-cost-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Count the steps","title":"How many indices can this scan check?","workspacePanel":"trace","options":[{"id":"up-to-n","label":"Up to n, one check per index when the target sits at or past the end","rationale":"The scan advances one position per step, so a target larger than everything forces a check at every index before falling off the end. For 10,000 elements that is 10,000 checks.","isCorrect":true},{"id":"about-log","label":"About log n, because sorted order lets it skip ahead","rationale":"This scan never skips; it reads strictly one index at a time. Nothing in the loop uses the sorted order to jump.","isCorrect":false},{"id":"constant","label":"A fixed handful, since it stops at the first big-enough value","rationale":"It stops early only when the target is small. When the target belongs near the end, there is no early stop and the count grows with n.","isCorrect":false}],"answer":"Up to n checks. The prompt asks for O(log n), so reading one index at a time is too slow. The sorted order has to eliminate more than one index per comparison.","summary":"The target can belong anywhere, including past the very last element."},{"id":"insertion-spec-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Pin the spec","title":"What is the insertion index, exactly?","workspacePanel":"trace","options":[{"id":"count-of-smaller","label":"The count of elements smaller than the target","rationale":"Every smaller element sits before the insertion point and everything else after it. Target 4 in [1, 3, 5, 7] has two smaller elements, so the index is 2.","isCorrect":true},{"id":"nearest-value","label":"The index of the closest value","rationale":"Closest can sit on the wrong side: 5 is closest to 4, but inserting at 5's index pushes 4 ahead of... nothing smaller than it? The spec is about order, not distance.","isCorrect":false},{"id":"middle-of-window","label":"Wherever the final midpoint stopped","rationale":"The final probe can land on either side of the target's true position. The answer comes from the final boundaries.","isCorrect":false}],"answer":"Insertion index = how many elements are smaller. That restatement is what the window's boundaries are about to earn.","summary":"For a target that isn't present in the array."},{"id":"idea-bridge","chapter":"The idea","kind":"info","eyebrow":"Beat the scan","title":"Halve the range instead of walking it","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"idea-bridge-state","state":{"nums":[1,3,5,7],"left":0,"right":3,"target":6}}]},"body":["The insertion index is just the count of elements smaller than the target. The scan finds it one step at a time; the sorted order means each comparison at a midpoint can rule out a whole half instead of a single index.","So keep a window [left, right] and probe its middle. The open question is what the boundaries prove outside the window, and what left means when the window finally empties on a miss."]},{"id":"sharper-invariant","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"What sharper promise does this loop need?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sharper-state","state":{"nums":[1,3,5,7],"left":2,"right":3,"target":6}}]},"options":[{"id":"partition-promise","label":"Everything before left is smaller than the target; everything after right is bigger","rationale":"Each boundary move is justified by a comparison, so the regions outside the window are sorted relative to the target. That partition survives the loop.","isCorrect":true},{"id":"old-promise-enough","label":"The old promise is enough","rationale":"On a miss, the old promise only says the window is empty. Placement needs to know what the excluded regions contain.","isCorrect":false},{"id":"right-marks-spot","label":"right ends up marking the insertion point","rationale":"right ends one below it. The region promise says smaller-than-target stops exactly at left, which is the insertion point.","isCorrect":false}],"answer":"left marks the first index not yet proven too small. When the window empties, left is the count of smaller elements, the insertion index from the spec.","summary":"Plain binary search promised \"if the target exists, it is inside [left, right]\"."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"A search destined to miss","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[1,3,5,7],"left":0,"right":3,"target":6}}]},"body":["Target 6 is not in [1, 3, 5, 7]. The loop runs exactly as in binary search, then the final boundaries give the insertion index."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the miss","title":"Trace the landing","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"window-empties","state":{"nums":[1,3,5,7],"left":3,"right":2,"target":6}},{"id":"target-below-all","state":{"nums":[1,3,5,7],"left":0,"right":0,"mid":0,"target":0}}]},"beats":[{"id":"window-empties","title":"What does left = 3 tell you?","summary":"Two midpoints proved 3 and 5 too small (left moved to 3), one proved 7 too big (right moved to 2). The loop is over.","prompt":"The window has emptied; left finished at 3.","options":[{"id":"count-landed","label":"Indices 0 through 2 all hold values smaller than 6","rationale":"left only ever advances past elements proven too small. Its resting place is the insertion index by construction, not by luck.","isCorrect":true},{"id":"overshot","label":"The search overshot and needs a step back","rationale":"Stepping back lands on 5, which is smaller than 6. Inserting there would push 6 ahead of a smaller value.","isCorrect":false},{"id":"coincidence","label":"left is just right + 1, an artifact of the loop ending","rationale":"left equals right + 1 because the smaller-than-target region and the bigger-than-target region meet exactly at the insertion point.","isCorrect":false}],"answer":"Return left. Three elements are smaller than 6, so 6 belongs at index 3, one past the end."},{"id":"target-below-all","title":"With the target below everything, where does left finish?","summary":"Same array, target 0: the very first comparison finds nums[1] too big, and every comparison after agrees.","prompt":"Same array, but the target is now 0, below everything in it.","options":[{"id":"left-never-moves","label":"Still at 0; no element was ever proven smaller","rationale":"left moves only when a midpoint is too small. Nothing is smaller than 0 here, so the count of smaller elements is 0 and the insertion is at the front.","isCorrect":true},{"id":"left-negative","label":"At -1, below the array","rationale":"left never decreases. right walks below the array to end the loop; left holds the answer.","isCorrect":false},{"id":"left-middle","label":"Wherever the last midpoint was","rationale":"The midpoints all said \"too big, look left,\" so they moved right. left = 0 throughout.","isCorrect":false}],"answer":"left = 0, so insert at the front. The same return left covers the front and one-past-the-end cases."}]},{"id":"return-mid-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"After the loop, could we return right instead?","summary":"left and right end one apart, so reaching for right when the loop exits looks like the same answer. right trails left by one, and that off-by-one files the target on the wrong side.","workspacePanel":"trace","pitfall":"The code below returns right after the loop instead of left.","whyItMatters":"Return left. When the loop exits, right has stepped to left - 1, so it points one slot before the insertion spot. That index can land in front of a value the target should follow.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"left, right = 0, len(nums) - 1\nwhile left <= right:\n    mid = (left + right) // 2\n    if nums[mid] == target:\n        return mid\n    if nums[mid] < target:\n        left = mid + 1\n    else:\n        right = mid - 1\nreturn right","steps":[{"id":"probe-too-big","title":"First probe is too big","codeLine":9,"summary":"nums = [1, 3, 5], target = 2. mid = 1, nums[1] = 3 > 2, so right moves down to 0.","state":{"nums":[1,3,5],"left":0,"right":0,"mid":1,"target":2}},{"id":"probe-too-small","title":"Second probe is too small","codeLine":7,"summary":"mid = 0, nums[0] = 1 < 2, so left moves up to 1. Now left = 1, right = 0 and the loop ends.","state":{"nums":[1,3,5],"left":1,"right":0,"mid":0,"target":2}},{"id":"right-trails-by-one","title":"right returns one too small","codeLine":10,"summary":"The function returns right = 0. But nums[0] is 1, which is smaller than 2. Inserting at 0 files the 2 ahead of a smaller value; the correct slot is left = 1, between 1 and 3.","state":{"nums":[1,3,5],"left":1,"right":0,"target":2}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let [left, right] = [0, (nums.length - 1)];\nwhile (left <= right) {\n    const mid = Math.floor((left + right) / 2);\n    if (nums[mid] === target) {\n        return mid;\n    }\n    if (nums[mid] < target) {\n        left = mid + 1;\n    } else {\n        right = mid - 1;\n    }\n}\nreturn right;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":12}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let [left, right] = [0, (nums.length - 1)];\nwhile (left <= right) {\n    const mid = Math.floor((left + right) / 2);\n    if (nums[mid] === target) {\n        return mid;\n    }\n    if (nums[mid] < target) {\n        left = mid + 1;\n    } else {\n        right = mid - 1;\n    }\n}\nreturn right;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":12}}},"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) == target) {\n        return mid;\n    }\n    if (nums.get(mid) < target) {\n        left = mid + 1;\n    } else {\n        right = mid - 1;\n    }\n}\nreturn right;","lineMap":{"1":1,"2":3,"3":4,"4":5,"5":6,"6":8,"7":9,"8":10,"9":11,"10":14},"statementBundles":{"1":{"startLine":1,"endLine":2},"5":{"startLine":6,"endLine":7},"9":{"startLine":11,"endLine":13}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"var (left, right) = (0, nums.Count - 1);\nwhile (left <= right) {\n    int mid = (left + right) / 2;\n    if (nums[mid] == target) {\n        return mid;\n    }\n    if (nums[mid] < target) {\n        left = mid + 1;\n    } else {\n        right = mid - 1;\n    }\n}\nreturn right;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":12}}},"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] == target) {\n        return mid;\n    }\n    if (nums[mid] < target) {\n        left = mid + 1;\n    } else {\n        right = mid - 1;\n    }\n}\nreturn right;","lineMap":{"1":1,"2":3,"3":4,"4":5,"5":6,"6":8,"7":9,"8":10,"9":11,"10":14},"statementBundles":{"1":{"startLine":1,"endLine":2},"5":{"startLine":6,"endLine":7},"9":{"startLine":11,"endLine":13}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The rule held on the main trace: keep halving toward the side that must hold the answer, and when the window empties, left lands on the insert spot.","Now push on the boundaries. Try target 6 in [1, 3, 5], a value larger than everything in the array. Where left finishes, and whether that index is even legal, is the next thing to settle."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[1,3,5,7],"left":0,"right":3,"target":6}}]}},{"id":"past-the-end-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"Is an out-of-bounds index really okay?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"past-end-state","state":{"nums":[1,3,5],"left":3,"right":2,"target":6}}]},"options":[{"id":"insertion-not-access","label":"Yes, because it is an insertion position","rationale":"Appending at the end is a legal insertion. len(nums) is exactly where a larger-than-everything target belongs; nothing ever reads nums[left] after the loop.","isCorrect":true},{"id":"clamp-it","label":"It should be clamped to len(nums) - 1","rationale":"Clamping files the target before the last element, which is smaller. That breaks the order the insertion was supposed to keep.","isCorrect":false},{"id":"special-case-append","label":"The append case needs its own check before the loop","rationale":"It already works: no comparison ever proves anything bigger, left sweeps the whole array, and the general return covers it.","isCorrect":false}],"answer":"Indices 0 through len(nums) are all valid insertion slots, one more slot than there are elements. The loop produces all of them with one return.","summary":"left finishes at 3 in a 3-element array."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Binary search's loop, one different last line.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[1,3,5,7],"left":0,"right":3,"target":6}}]},"body":["Use inclusive bounds, compare nums[mid] with target, return mid on a hit, move past mid on a miss, and return left when the window empties."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the boundary search","summary":"Initialize the bounds, compute mid, compare nums[mid] with target, narrow the bounds, and return left on a miss.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"The same window, asked a sharper question: left ends as the count of smaller elements.","workspacePanel":"code","body":["Binary search's boundaries carry placement information. On a miss, return left because it is the first index whose value is not proven smaller than target.","The lower-bound family uses the same shape: first-bad-version, find-first-occurrence, and every \"where does X begin\" question return the left boundary."],"takeaways":[{"title":"left counts smaller elements","body":"It advances only past elements proven smaller than the target, so its resting place is the insertion index by construction."},{"title":"Use the final boundary","body":"The final probe lands wherever halving happened to put it. left and right record which side of the target each excluded region belongs to."},{"title":"len(nums) is a valid answer","body":"There are n + 1 insertion slots in an n-element array. The loop produces all of them from one return left."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"executionStyle":"solution-method","syntheticTestConfig":{"inputShape":"array-target","primaryParam":"nums","secondaryParam":"target","sizeMetric":"length","constraints":["sorted","distinct"]}}
