Search Insert Position
Pattern: Binary search on sorted arrays
The index of the target if it is there, or the index where it would be inserted. Both are the same thing, the first index holding a value at least the target, which is the lower bound.
The problem
You are given a sorted array of different whole numbers and a target. Return the index of the target if it is in the
array. If not, return the index where it would go to keep the array sorted. For example, [1, 3, 5, 6] gives 2 for
target 5, 1 for target 2, 4 for target 7 and 0 for target 0.
The function name searchInsert matches LeetCode. Use the link above for the exact statement and limits. The search
must take O(log n) time.
Think first
- If the target is present, which index holds the first value at least the target?
- If the target is missing, which index holds the first value bigger than it?
- What should the answer be when every value is smaller?
Hints
Brute force, and why it fails
Walk from the left and return the first index whose value is at least the target, or n: O(n). The array is sorted,
so binary search finds that index in O(log n).
The key insight
"Where is it, or where would it go" is the first yes of the test nums[i] ≥ target. Every no comes before every yes,
so binary search for the boundary.
Dry run
nums = [1, 3, 5, 6] and target = 2. The answer is in lo..hi, where hi = 4 means after the end.
The plan
lo = 0, hi = n
while lo < hi:
mid = lo + (hi - lo) / 2
if nums[mid] < target: lo = mid + 1
else: hi = mid
return lo
Complexity
- Time
O(log n)- Space
O(1)
The range halves each step.
Edge cases
- Target bigger than everything: the answer is
n. - Target smaller than everything: the answer is 0.
- One value: 0 or 1.
I've built my logic, show the code
Java
class Solution {
public int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length; // answer is in [lo, hi]; hi = n means "after the end"
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) lo = mid + 1; // mid is too small, so the answer is after it
else hi = mid; // mid could be the answer
}
return lo;
}
}C++
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int lo = 0, hi = static_cast<int>(nums.size()); // answer is in [lo, hi]; hi = n means "after the end"
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) lo = mid + 1; // mid is too small, so the answer is after it
else hi = mid; // mid could be the answer
}
return lo;
}
};Python
class Solution:
def searchInsert(self, nums: list[int], target: int) -> int:
lo, hi = 0, len(nums) # answer is in [lo, hi]; hi = n means "after the end"
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1 # mid is too small, so the answer is after it
else:
hi = mid # mid could be the answer
return loCommon mistakes
- Starting
hiatn - 1, which can never returnn. - Using
hi = mid - 1withwhile lo < hi, which can skip the answer. - Returning -1 when the target is missing. The question wants the insert position.