Classic binary search but with a small twist at the end.
Use binary search to find the target or the insertion point. Maintain low and high pointers, and at each step compare the middle element with the target. If found, return the index; otherwise, after the loop, low will be the insertion index.
Pro tip: Clarify that the array has distinct integers and is sorted, so binary search is optimal. Mention that the same algorithm can be implemented using lower_bound in C++ or bisect_left in Python, but be prepared to write it from scratch.
Restate the problem to ensure understanding: sorted distinct integers, find target or insertion index, O(log n) required. Ask if there are any constraints on array size or duplicates (though distinct is given).
Explain that binary search is the natural choice for O(log n) on a sorted array. Define low = 0 and high = n (or n-1) and decide on the loop condition.
While low < high (or low <= high), compute mid, compare nums[mid] with target. If equal, return mid. If nums[mid] < target, set low = mid + 1; else set high = mid.
If the loop ends without finding the target, return low (or high+1 depending on variant) as the insertion point to maintain sorted order.
Walk through edge cases: target smaller than all, larger than all, empty array, single element. Confirm O(log n) time and O(1) space.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.