35. Search Insert Position
Asked at 11Bloomberg58Microsoft57Amazon56Google55Meta49Grammarly85tcs46Accenture54Zoho42Infosys39Yandex28
Problem
nums is sorted with distinct values. Return the index of target if present, otherwise the index where it would be inserted to keep the order, in O(log n).
Example: nums = [1,3,5,6]: target = 5 → 2; target = 2 → 1; target = 7 → 4
First index with nums[i] >= target (lower bound). Uses the template with hi = n.
Complexity: O(log n).
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] >= target:
hi = mid
else:
lo = mid + 1
return lo
assert Solution().searchInsert([1, 3, 5, 6], 5) == 2
assert Solution().searchInsert([1, 3, 5, 6], 2) == 1
assert Solution().searchInsert([1, 3, 5, 6], 7) == 4
class Solution {
public int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] >= target) hi = mid; else lo = mid + 1;
}
return lo;
}
}
func searchInsert(nums []int, target int) int {
lo, hi := 0, len(nums) // first index with nums[i] >= target
for lo < hi {
mid := lo + (hi-lo)/2
if nums[mid] >= target {
hi = mid
} else {
lo = mid + 1
}
}
return lo
}