DevPath

← All problems

Binary Search

Easy binary-search · arrays

Description

Given a sorted array of distinct values, return the index of target, or -1 if it is absent.

Constraints

1 <= n <= 100000

Examples

Input: nums = [-1,0,3,5,9,12], target = 9

Output: 4

Hints (1)
  • Halve the search space each step by comparing with the middle value.

Solutions

Classic inclusive binary search. · Time O(log n) · Space O(1)

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

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

Create account