#35
Easy Algorithms Search insert position
Array Binary Search
50.8% acceptance
Jan 12, 2026
18658
890
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.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
let mut left = 0;
let mut right = nums.len();
while left < right {
let mid = left + (right - left) / 2;
if nums[mid] == target {
return mid as i32;
} else if nums[mid] < target {
left = mid + 1;
} else {
right = mid;
}
}
left as i32
}
}