Search Insert Position
Difficulty: Easy · Pattern: Binary Search · LeetCode #35
nums is sorted with distinct values. Return the index of target if found; otherwise the index where it would be inserted to keep the order. O(log n).
Examples
text
nums = [1, 3, 5, 6], target = 5 → 2
nums = [1, 3, 5, 6], target = 2 → 1
nums = [1, 3, 5, 6], target = 7 → 4Hints
- Both cases ask for the same thing: the first index whose value is ≥ target.
Approach
Binary search the lower bound in the half-open range [0, n): if nums[mid] < target, the answer is right of mid (lo = mid + 1); otherwise it's at or left of mid (hi = mid). When lo == hi, that's the answer (it can be n). Equivalent to Python's bisect_left.
Complexity
Time: O(log n). Space: O(1).
Python solution
def searchInsert(nums, target):
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return loJavaScript solution
function searchInsert(nums, target) {
let lo = 0, hi = nums.length;
while (lo < hi) { const mid = (lo + hi) >> 1; if (nums[mid] < target) lo = mid + 1; else hi = mid; }
return lo;
}