DevPath

← All problems

Search Insert Position

Easy binary-search · arrays

Description

Given a sorted distinct array and a target, return its index, or the index where it should be inserted to keep the array sorted.

Constraints

1 <= n <= 100000

Examples

Input: nums = [1,3,5,6], target = 5

Output: 2

Hints (1)
  • Binary search for the first index whose value is >= target.

Solutions

Lower-bound binary search. · Time O(log n) · Space O(1)

func searchInsert(nums []int, target int) int {
    lo, hi := 0, len(nums)
    for lo < hi {
        mid := (lo + hi) / 2
        if nums[mid] < target {
            lo = mid + 1
        } else {
            hi = mid
        }
    }
    return lo
}

Create a free account to submit solutions, track progress and save problems.

Create account