Binary Search
Easy · Binary Search · Array · Binary Search
Problem
Given a sorted array of distinct integers nums and a target, return the index of target, or -1 if it is absent.
Your solution must run in O(log n) time.
Examples
Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4
Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1
Not present.
Constraints
- 1 <= len(nums) <= 10^4
- All values are unique and sorted ascending
- -10^4 < nums[i], target < 10^4
Approaches
- Iterative, closed interval [lo, hi] — time O(log n), space O(1)
Related problems
Start free on Cariara · Coding problems · System design studio