InterviewPrepKit

Home / Coding / Binary Search

Search Insert Position

easy Original β†—
Solving tips
  • Reframe 'index of target or where it would go' as one question: the first index where nums[i] >= target (lower bound), which unifies the found and not-found cases.
  • Use the half-open template: lo=0, hi=len(nums) (exclusive), while lo < hi: if nums[mid] < target then lo=mid+1 else hi=mid; return lo.
  • Target O(log n) time, O(1) space; bisect.bisect_left gives the same answer if you want the one-liner.
  • Pitfall: initializing hi = len(nums)-1 with this convention makes the 'insert at the end' answer (len(nums)) unreachable; keep hi exclusive.

Problem

Given a sorted array of distinct integers nums and a target value target, return the index of target if it is present. If it is not present, return the index where it would be inserted to keep the array sorted.

Your algorithm must run in O(log n) time.

Examples

  • Input: nums = [1, 3, 5, 6], target = 5 β†’ Output: 2 (5 is already at index 2.)
  • Input: nums = [1, 3, 5, 6], target = 2 β†’ Output: 1 (2 would slot in between 1 and 3, taking index 1.)
  • Input: nums = [1, 3, 5, 6], target = 7 β†’ Output: 4 (7 is bigger than everything, so it goes at the end.)

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i], target <= 10^4
  • nums contains distinct values sorted in ascending order.
  • Required time complexity: O(log n).

Think about it first

Hint 1 Whether or not the target is present, the answer is the same well-defined position. Can you phrase both cases ("found at i" and "insert at i") as one question about the array?
Hint 2 The answer is the index of the first element that is greater than or equal to the target (or the array length if none is). That's the classic "lower bound" query β€” and the array of answers to "is nums at index i >= target?" looks like F, F, …, F, T, T, …, T.
Hint 3 Binary search for that first True. Keep `lo = 0`, `hi = len(nums)` (exclusive), and while `lo < hi`: if `nums[mid] < target`, the boundary is right of mid, so `lo = mid + 1`; otherwise `hi = mid`. When they meet, `lo` is the answer β€” no special found/not-found cases needed.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.