Search Insert Position

EasyBinary Search · Lower Bound🧩 Binary SearchLeetCode #35 ↗Updated

Problem

You get a sorted array nums of distinct integers and a value target. Return the index of target if it is present; otherwise return the index where it would have to be inserted so the array stays sorted. Aim for O(log n) time.
Inputnums = [1,3,5,6], target = 5Output2
Inputnums = [1,3,5,6], target = 2Output1
Inputnums = [1,3,5,6], target = 7Output4

1 ≤ n ≤ 104  ·  -104 ≤ nums[i], target ≤ 104  ·  nums sorted ascending, distinct  ·  O(log n) required

Try it yourself

Java
class Solution {
    public int searchInsert(int[] nums, int target) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Both cases have the same answer: the first index whose value is ≥ target (the lower bound). That predicate is false…false, true…true across the array, so binary search can find the boundary directly.
PatternBinary Search

Instinct Sorted data, a rotated array, or find the min/max X that works where a yes/no test flips only once - halve the search space every step.

Memory hack Find the fence - every candidate reads NO NO NO YES YES, and binary search just walks to where the fence stands.

Open the Binary Search guide →

Approaches

Brute ForceLinear Scan for First ≥ target

Time O(n)Space O(1)

Walk left to right and stop at the first element that is not smaller than target — that is either the match or the slot it belongs in. If no such element exists, the target goes after everything, at index n.

Java
public int searchInsert(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] >= target) return i; // first slot that can hold target
    }
    return nums.length; // target is larger than every element
}

Correct and tiny, but ignores sortedness and misses the O(log n) requirement.

At a glance

LevelApproachTimeSpace
Brute ForceLinear Scan for First ≥ targetO(n)O(1)
OptimalBinary Search on the Lower BoundO(log n)O(1)
Common pitfalls
  • Starting with hi = n - 1 and forgetting the “insert at the end” case.
  • Writing hi = mid - 1 in the lower-bound template — can skip the answer.
  • Computing (lo + hi) / 2 carelessly; prefer lo + (hi - lo) / 2.
Interview tips
  • Reframe both cases as “first index with value ≥ target” before coding.
  • State the loop invariant: the answer always stays inside [lo, hi].
  • Mention that Java’s Arrays.binarySearch encodes the insert point as -(pos) - 1.
Pattern
Lower-bound binary search → sorted data plus “first position where a condition becomes true”.
My notes saved in this browser