Given a sorted array of distinct integers nums and a target value, return the index if the target is found. If not, return the index where it would be inserted in order. You must write an algorithm with O(log n) runtime complexity.
nums = [1,3,5,6], target = 52nums = [1,3,5,6], target = 21nums = [1,3,5,6], target = 74lo = 0, hi = nums.length − 1lo ≤ hi: compute mid = lo + (hi−lo)/2nums[mid] == target → return mid (found)nums[mid] < target → lo = mid + 1 (search right half)hi = mid − 1 (search left half)lo is the insertion point — return lolo is the Insert PositionLoop invariant: at every step the answer lies in [lo, hi+1]. When lo > hi the range collapses and lo points to the first index where nums[lo] > target — exactly where target must be inserted to preserve sorted order. This works whether target is smaller than all elements (lo stays 0), larger than all (lo becomes n), or anywhere in between.
Scanning for the first number that is at least the target is O(n). Binary search finds it in O(log n).
Run a normal binary search. If the target is never found, low ends at the first index whose value is bigger than the target. That is exactly the insert position.
When binary search misses, low lands on the insert position. That makes low the first index with a value at least the target.
Run the animation above on your own input, or watch the 1:08 video explanation of Search Insert Position with a dry run and Java code.