Search Insert Position
EasyTop Interview 150 Binary SearchGrammarlyProblem
You get a sorted array nums of distinct integers and a number target.
If target is in the array, return its index. If it is not, return the index where it would have to be
placed to keep the array sorted. Your solution has to run in O(log n) time.
Constraints
- 1 ≤ nums.length ≤ 10⁴
- −10⁴ ≤ nums[i], target ≤ 10⁴
- nums holds distinct values in increasing order
Examples: pick one to animate
Solutions
TimeO(log n)
SpaceO(1)
Time: Each probe discards half of the range between lo and hi, so there are about log2(n) probes.
Space: Only lo, hi and mid are stored.
Search the half-open range [lo, hi), with hi = n. If nums[mid] is less than the target,
the answer is right of it, so lo = mid + 1. Otherwise mid may be the answer, so hi = mid.
When the range closes, lo is the insert position.