Stage 1: Foundations·Binary Search Mastery
Easy#355 min readBinary SearchArraysLeetCode

Search Insert Position

Lower bound

Lower bound. Understand why lo ends up at the insertion point.

Published Apr 15, 2026

Problem

Given a sorted array nums and a target target, return the index where target should be inserted to keep the array sorted.

If target already exists, return its current index.

Input
nums = [1, 3, 5, 6], target = 5
Output
2
Input
nums = [1, 3, 5, 6], target = 2
Output
1
Explanation
2 belongs between 1 and 3.

Intuition

This is not a different problem from #704. It is the lower bound version of binary search: find the first position where nums[i] >= target.

That phrasing is useful because it removes the ambiguity around "found vs not found." Whether target is already present or not, the lower bound gives the right answer. If the value exists, that first >= position is its index; if it does not, it is the insertion point.

Again, a half-open interval [lo, hi) keeps the invariant clean.

Approach

Lower Bound Binary Search

TimeO(log n)
SpaceO(1)
Recommended

Search for the first index whose value is not less than target.

  • If nums[mid] < target, the lower bound must be to the right, so move lo to mid + 1.
  • Otherwise, the lower bound is at mid or to the left, so move hi to mid.

When the loop ends, lo is exactly the insertion index.

impl Solution {
    pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
        let mut lo = 0usize;
        let mut hi = nums.len();

        while lo < hi {
            let mid= lo + (hi - lo) / 2;
            if nums[mid] < target {
                lo= mid + 1;
            } else {
                hi= mid;
            }
        }

        lo as i32
    }
}
Rust · runnable

Trace

Insert target = 2 into nums = [1, 3, 5, 6]:

lohimidnums[mid]action
0425move hi to 2
0213move hi to 1
0101move lo to 1

The loop ends with lo = 1, which is the correct insertion point.

Edge cases

  • Target already exists — lower bound returns its leftmost position, which is exactly the required index for this problem because the array has distinct values.
  • Insert at the front — if target is smaller than every element, lo stays at 0.
  • Insert at the end — if target is larger than every element, lo becomes nums.len().

Takeaway

"Find the first place something becomes true" is the lower-bound pattern. It shows up in insertion points, first bad versions, and many optimization checks.

If #704 is "search for equality," #35 is "search for the boundary."

More in Binary Search Mastery