Skip to content
CodeShare
All problems

Binary Search

Find a target in a sorted array in logarithmic time.

EasyArraysBinary search

Given an array of integers nums sorted in ascending order and an integer target, return the index of target in nums, or -1 if it isn't there.

All values in nums are distinct. Aim for an O(log n) solution.

Examples

Example 1
Input
nums = [-1, 0, 3, 5, 9, 12], target = 9
Output
4
Why
9 is at index 4.
Example 2
Input
nums = [-1, 0, 3, 5, 9, 12], target = 2
Output
-1
Why
2 isn't in the array.

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 < nums[i], target < 10^4
  • nums is sorted in ascending order with no duplicates.