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.