Search Insert Position
Find the index of target if present or the insertion index where it belongs using the lower-bound binary search template.
01The problem
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
| Input | Output | Why |
|---|---|---|
nums = [1, 3, 5, 6], target = 5 | 2 | Target 5 exists at index 2 |
nums = [1, 3, 5, 6], target = 2 | 1 | 2 would be inserted between 1 and 3 (at index 1) |
nums = [1, 3, 5, 6], target = 7 | 4 | 7 is larger than all elements, goes at the end |
nums = [1, 3, 5, 6], target = 0 | 0 | 0 is smaller than all elements, goes at index 0 |
Constraints: 1 to 10,000 integers, sorted ascending with distinct values.
02How to spot it
- The array is sorted and asks for the position where an element exists or belongs.
- The question is equivalent to finding the first index with value ≥ target (the lower bound).
- If target is larger than all elements, the answer can be
nums.length, meaning the search space is half-open[0, n].
So: lower-bound binary search on a half-open range.
03Pseudocode
lo = 0 ; hi = n
while lo < hi:
mid = lo + (hi - lo) / 2
if a[mid] < target: lo = mid + 1
else: hi = mid
return lo- We search for the first index with value ≥ target.
- Too small (
a[mid] < target)? Target must be strictly to the right:lo = mid + 1. - Large enough (
a[mid] >= target)?miditself could be the answer: keep it by settinghi = mid.
04Watch it work
Search for insertion position of 2 in half-open range [0 .. 4). Target might belong at index 4.
Pseudocode
- lo = 0 ; hi = n
- while lo < hi:
- mid = lo + (hi - lo) / 2
- if a[mid] < target: lo = mid + 1
- else: hi = mid
- return lo
Variables
- lo
- 0
- hi
- 4
- target
- 2
05Step-by-step dry run
- 110315263lohi
Search for insertion position of 2 in half-open range [0 .. 4). Target might belong at index 4.
lo = 0hi = 4target = 2
- 210315263lomidhi
Mid = 2 (value = 5). Compare with target 2.
lo = 0hi = 4mid = 2value = 5target = 2
- 310315263lohi
a[2] (5) ≥ target (2): index 2 could be the insertion point. Set hi = 2.
lo = 0hi = 2target = 2
- 410315263lomidhi
Mid = 1 (value = 3). Compare with target 2.
lo = 0hi = 2mid = 1value = 3target = 2
- 510315263lohi
a[1] (3) ≥ target (2): index 1 could be the insertion point. Set hi = 1.
lo = 0hi = 1target = 2
- 610315263lomidhi
Mid = 0 (value = 1). Compare with target 2.
lo = 0hi = 1mid = 0value = 1target = 2
- 710315263lohi
a[0] (1) < target (2): target must go after index 0. Set lo = 1.
lo = 1hi = 1target = 2
- 810315263insert
Range converged at lo = hi = 1. Target 2 belongs at index 1.
lo = 1result = 1
06Java solution
public class SearchInsertPosition {
public static int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length; // answer can be nums.length
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) lo = mid + 1;
else hi = mid; // mid might be the answer
}
return lo; // first index with value >= target
}
public static void main(String[] args) {
System.out.println(searchInsert(new int[]{1, 3, 5, 6}, 5));
System.out.println(searchInsert(new int[]{1, 3, 5, 6}, 2));
System.out.println(searchInsert(new int[]{1, 3, 5, 6}, 7));
System.out.println(searchInsert(new int[]{1, 3, 5, 6}, 0));
}
}2 1 4 0
Tricky lines, decoded
hi = nums.length: Inserting after the last element is a valid outcome (e.g., target 7 in[1, 3, 5, 6]belongs at index 4), sohistarts atn.else hi = mid: Ifnums[mid] >= target,miditself might be the very first index meeting the condition. Never writehi = mid - 1here, or you might skip past the answer.
07Why it works
The lower-bound template partitions the array into two zones: elements strictly less than target on the left, and elements greater than or equal to target on the right. Throughout the search, every index < lo has nums[i] < target, and every index ≥ hi has nums[i] >= target. When lo meets hi, the range has collapsed to the exact boundary between the two zones.
Invariant: nums[0 .. lo - 1] < target and nums[hi .. n - 1] >= target.
08Time and space
- Time: O(log n). The half-open range
[lo, hi)is cut in half on every step, taking at most 14 steps for 10,000 elements. - Space: O(1). Only three scalar pointers are maintained.
09Edge cases
| Input | Output | Why it matters |
|---|---|---|
[1, 3, 5, 6], target = 7 | 4 | Insert after the last element (returns n) |
[1, 3, 5, 6], target = 0 | 0 | Insert before the first element (returns 0) |
[1], target = 1 | 0 | Single element, target found |
[1], target = 2 | 1 | Single element, target inserted after |
[2, 4], target = 3 | 1 | Insertion between two elements |
10Common mistakes
- Initializing
hi = n - 1. If target is greater than all elements in the array,hican never reachn, causing an incorrect answer when inserting at the end. - Writing
hi = mid - 1in this template. This skips the answer whennums[mid]is the exact target or insertion slot. - Returning -1 on a miss. This problem always has a valid answer: if the element is absent, its insertion slot must be returned.
11Other approaches
| Approach | Time | Space | Use when |
|---|---|---|---|
| Linear scan | O(n) | O(1) | Tiny arrays |
| Lower bound template | O(log n) | O(1) | Default interview answer |
Arrays.binarySearch | O(log n) | O(1) | Production: decode -insertion - 1 |
TreeSet.ceiling() | O(log n) | O(n) | Dynamic collections with insertions |
12In the interview
- How to write upper bound (first value > target)? Change
if (nums[mid] < target)toif (nums[mid] <= target).
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why do we initialize hi to nums.length instead of nums.length - 1 in searchInsert?
2. In this template, why do we write hi = mid instead of hi = mid - 1?
14Solve it yourself
Try it on LeetCode #35.