InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Binary Search

Search Insert Position

easy Original ↗ 00:00

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 present at index 2.)
  • Input: nums = [1, 3, 5, 6], target = 2 → Output: 1 (2 belongs between 1 and 3, at index 1.)
  • Input: nums = [1, 3, 5, 6], target = 7 → Output: 4 (7 is larger than every element, 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug