Binary search for the lower bound
Find the first index where nums[i] >= target. That is the found index, or where target would be inserted.
Same halving as binary search. When the range collapses, lo is the insertion point — including n when the target is larger than every value.
Algorithm
- While
lo < hi, probemid. - If
nums[mid] < target, search the right half; else search the left (keepingmid). - Return
lo.
- Time
- O(log n)
- Space
- O(1)
class Solution: def searchInsert(self, nums: list[int], target: int) -> int: lo, hi = 0, len(nums) while lo < hi: mid = (lo + hi) // 2 if nums[mid] < target: lo = mid + 1 else: hi = mid return lo