I knew the problem immediately but fumbled the pointer logic on my first pass.
Use binary search to find the target or the insertion point by maintaining low and high pointers. At each step, compare the middle element with the target and adjust the search range accordingly. Return low when the search ends, as it will be the index where the target should be inserted.
Pro tip: Emphasize that the algorithm runs in O(log n) time and O(1) space, which is optimal for this problem. Also, mention that handling edge cases like empty arrays or targets outside the range is straightforward with this approach.
Confirm that the array is sorted, contains distinct integers, and that you need to return the index if found or the insertion index otherwise. Ask about edge cases like empty array or target not present.
Set low = 0 and high = len(nums) - 1 to define the search space.
While low <= high, compute mid = (low + high) // 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 maintain sorted order. Return low.
Walk through examples like target present, target smaller than all, target larger than all, and empty array to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.