lo = 0, hi = n; while lo < hi: if nums[mid] >= target, hi = mid; else lo = mid + 1. Return lo.
Approach 1
class Solution {
public int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] >= target) hi = mid;
else lo = mid + 1;
}
return lo;
}
}
Verdict: One template, no special cases.
Before you submit
Edge cases and common mistakes
Test these inputs
Insert at the front (0)
Insert at the end (n)
Mistakes people make
Starting hi at n − 1, which can never return n.
Interview
Follow-up questions
What does Java's Arrays.binarySearch return when the key is missing?