35. Search Insert Position
Easy ↗ Open on LeetCode Source: Misc
Quick review
- Pattern
- Binary Search
- Time
- O(logN)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven a sorted array of distinct integers and a target value, find the index where the target exists, or determine the index where it would be inserted to keep the array sorted.
Approach
- Use standard binary search, maintaining
loandhias inclusive bounds. - At each step, compare the midpoint value to the target and halve the search space.
- When the target is found, return its index immediately.
- When the loop ends without a match,
lohas converged to the leftmost position where the target would belong — the first index whose element is strictly greater than the target — so returnlodirectly.
#include <vector>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int lo = 0, hi = static_cast<int>(nums.size()) - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; // avoids potential overflow vs (lo+hi)/2
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
// lo is the insertion point: all elements to its left are < target,
// all elements from lo onward are > target.
return lo;
}
}; Time O(log n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left=0;
int right=nums.size()-1;
while(left<=right){
int mid=(left+right)/2;
if(nums[mid]==target){
return mid;
}
else if(nums[mid]>target){
right=mid-1;
}
else{
left=mid+1;
}
}
return left;
}
};
// nums = [1,3,5,6], target = 5
// l=0 -> 2
// r=3
// mid=1 -> 2
// nums = [1,3,5,6], target = 2
// l=0
// r=3 -> 0
// mid=1 -> 0
// Time Complexity: O(logN)
// Space Complexity: O(1)
Time O(logN) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.