Example 1
- Input
- nums = [1, 3, 5, 6], target = 2
- Output
- 1
The value 2 is absent and belongs between 1 and 3, so the answer is 1.
You are given a sorted array of distinct integers and a target value. Return the index of the target when present, or the index where it belongs in sorted order when absent.
Given a sorted array of distinct integers nums and a target value target, return the index if the target is found.
If the target is absent, return the index where it would be inserted in order. The required solution runs in time.
nums contains distinct values sorted in ascending order.The value 2 is absent and belongs between 1 and 3, so the answer is 1.
The value 5 is found at index 2, so the answer is 2.
The value 7 is absent and belongs after every element, so the answer is 4.
The only value is greater than 2, so insert before it at index 0. There is no empty-array case under the constraints.
The insertion index is the number of array values smaller than the target. This also gives the existing index when the target is present, because the array is sorted and distinct. In Example 1, only 1 is smaller than 2, so index 1 separates values below 2 from values above it. Binary search locates that separation by ruling out half the remaining positions after each comparison.
Reveal Linear Scan: intuition, complexity, and code
left and right finish when the target is missing: left always stops at the first larger element.left after the loop instead of -1, since an exact hit already returns from inside the loop.0 in [1, 3, 5, 6], returns 0.7 in [1, 3, 5, 6], returns nums.length.0 when the target fits before it and 1 when it fits after it.right or mid instead of left after the loop, which points one slot too early.left < right instead of left <= right, which skips the final single-element check.mid as (left + right) / 2 in a fixed-width language without the overflow-safe form left + (right - left) / 2.A standard binary search already finds insertion points: when the loop ends, left is the lower bound where a missing value belongs.