Given a sorted array of distinct integers and a target value, return the index of the target if it is found. If not, return the index where it would be inserted to keep the array sorted.
You must write an algorithm with O(log n) runtime.
We use analytics and advertising cookies to understand how the site is used and whether our ads on Facebook and Instagram work. They are set only if you accept. See our Privacy Policy for details.
Given a sorted array of distinct integers and a target value, return the index of the target if it is found. If not, return the index where it would be inserted to keep the array sorted.
You must write an algorithm with O(log n) runtime.
An easy binary search problem, graded against 6 test cases (3 of them hidden).
Halving a search space each step - on sorted arrays, and on answers themselves.
Reach for it when you see: A sorted input, or a monotonic "is this value feasible?" predicate you can binary search over.
More Binary Search problems →The insight is that a failed binary search already knows where the value belongs - the standard version just throws that away by returning -1. Written as a lower-bound search, the final position is the answer whether the target was present or not.
Use the half-open form: `lo = 0`, `hi = nums.length` (one past the end), and loop while `lo < hi`, moving `lo = mid + 1` when `nums[mid] < target` and `hi = mid` otherwise. When they meet, `lo` is the first index whose value is not less than the target - which is the target's index if present, and its insertion point if not. There is no separate found/not-found branch at all.
The half-open convention is what makes the edge cases disappear: inserting past the end returns `nums.length` without a special case, and `hi = mid` rather than `mid - 1` avoids skipping the candidate.
One habit worth carrying: compute `mid` as `lo + ((hi - lo) >> 1)` rather than `(lo + hi) / 2`, which overflows in fixed-width integer languages - a famous bug that sat in the JDK's binary search for years.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.