#35

Search Insert Position

Easy Lower bound

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

In a sorted array of distinct values, return the index of target, or the index where it would be inserted to keep the order.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: where is target, or where would it go?

Why this works: when the search fails, lo ends at the first value bigger than target, which is the insert spot.

Example: [1, 3, 5, 6], target 2

mid 1 (3) > 2 → hi 0mid 0 (1) < 2 → lo 1answer 1

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Returning hi or mid at the end — it's lo.

Solve on LeetCode ↗
Complexity
  • Time: O(log n).
  • Space: O(1).
Topic: Binary Search
🎬 Episodes 21–23: video coming soon