Skip to content
AI360Xpert
Beta
Difficulty: EasyBinary Search

Search Insert Position

Problem in Plain English

You are given a sorted array of distinct integers and a target value. Return the index of the target when present, or the index where it belongs in sorted order when absent.

Problem Statement

Given a sorted array of distinct integers nums and a target value target, return the index if the target is found.

If the target is absent, return the index where it would be inserted in order. The required solution runs in O(logn)O(log n) time.

Constraints

  • 1≤n≤1041 \leq n \leq 10^4, where n is nums.length.
  • −104≤nums[i]≤104-10^4 \leq nums[i] \leq 10^4.
  • nums contains distinct values sorted in ascending order.
  • −104≤target≤104-10^4 \leq target \leq 10^4.

Examples

Example 1

Input
nums = [1, 3, 5, 6], target = 2
Output
1

The value 2 is absent and belongs between 1 and 3, so the answer is 1.

Example 2

Input
nums = [1, 3, 5, 6], target = 5
Output
2

The value 5 is found at index 2, so the answer is 2.

Example 3

Input
nums = [1, 3, 5, 6], target = 7
Output
4

The value 7 is absent and belongs after every element, so the answer is 4.

Example 4

Input
nums = [5], target = 2
Output
0

The only value is greater than 2, so insert before it at index 0. There is no empty-array case under the constraints.

Intuition

The insertion index is the number of array values smaller than the target. This also gives the existing index when the target is present, because the array is sorted and distinct. In Example 1, only 1 is smaller than 2, so index 1 separates values below 2 from values above it. Binary search locates that separation by ruling out half the remaining positions after each comparison.

Approaches

Linear Scan

Solution Details

Reveal Linear Scan: intuition, complexity, and code

Hints

Hint 1
A sorted input with a logarithmic time requirement points directly at binary search rather than a scan.
Hint 2
Trace where left and right finish when the target is missing: left always stops at the first larger element.
Hint 3
Return left after the loop instead of -1, since an exact hit already returns from inside the loop.

Edge Cases

  • A target below every element, such as 0 in [1, 3, 5, 6], returns 0.
  • A target above every element, such as 7 in [1, 3, 5, 6], returns nums.length.
  • A single-element array returns 0 when the target fits before it and 1 when it fits after it.

Common Mistakes and Interview Tips

  • Returning right or mid instead of left after the loop, which points one slot too early.
  • Looping while left < right instead of left <= right, which skips the final single-element check.
  • Computing mid as (left + right) / 2 in a fixed-width language without the overflow-safe form left + (right - left) / 2.

Key Takeaway

A standard binary search already finds insertion points: when the loop ends, left is the lower bound where a missing value belongs.