TRT
Sign in
easyCoreLeetCode#lower bound

Search insert position

Return the index of a target in a sorted array, or where it would be inserted: the lower bound.

The Runtime Theory Team1 min read
Taught inLower and upper boundsPro — members onlyInstead of asking whether a value is present, ask where the first element that is at least x sits. That one question finds first and last occurrences, counts duplicates and gives insertion points, with no special cases.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [1, 3, 5, 6], target = 5

out2

innums = [1, 3, 5, 6], target = 2

out1

innums = [1, 3, 5, 6], target = 7

out4

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

  1. Search for the first index with nums[i] >= target.
  2. If every element is smaller, the answer is len(nums), which the half-open loop returns naturally.
  3. 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.

Not started

Sign in to save your learning progress.

Sign in to save