SDE & MLE Prep

35. Search Insert Position

Problem

nums is sorted with distinct values. Return the index of target if present, otherwise the index where it would be inserted to keep the order, in O(log n).

Example: nums = [1,3,5,6]: target = 5 → 2; target = 2 → 1; target = 7 → 4

First index with nums[i] >= target (lower bound). Uses the template with hi = n.

Complexity: O(log n).

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:
                hi = mid
            else:
                lo = mid + 1
        return lo