Given a sorted array of distinct integers and a target, return the index of the target if present, otherwise the index where it would be inserted in order.
Before you code
Both cases ask the same question: the first index whose value is at least the target. That is exactly the lower bound, with no special case for "found".
Hints
- Search for the first index with
nums[i] >= target. - If every element is smaller, the answer is
len(nums), which the half-open loop returns naturally. - In Python this is
bisect.bisect_left; write it yourself first.
Production & complexity notes
When solving Search insert position on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Lower and upper bounds to reinforce the underlying pattern.
What it practices
Lower bound as an insertion point, from Lower and upper bounds.