Binary search, so you know immediately it's binary search.
Use binary search to find the target or the insertion point in O(log n) time. Maintain low and high pointers, and at each step compare the middle element with the target to decide which half to search. If the target is not found, the low pointer will indicate the correct insertion index.
Pro tip: Emphasize that the algorithm handles edge cases like empty array, target smaller than all elements, and target larger than all elements, and that the return value is always the first index where the target could be inserted to keep the array sorted.
Confirm that the array is sorted, contains distinct integers, and that the solution must run in O(log n) time. Ask if there are any constraints on the array size or integer range.
Explain that binary search is the optimal approach because it halves the search space each iteration, achieving O(log n) time complexity.
Initialize low = 0 and high = n-1. Maintain the invariant that the target should be inserted at index low if not found, and that all elements before low are less than the target, while all elements after high are greater than the target.
While low <= high, compute mid = low + (high - low) // 2. If nums[mid] == target, return mid. If nums[mid] < target, set low = mid + 1. Else, set high = mid - 1.
After the loop, low is the index where the target should be inserted to keep the array sorted. Return low.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.