☰ All problems

23. Binary Search

EasyArrayBinary Search

You are given an array nums of distinct integers sorted in ascending order, and an integer target.

Return the index of target in nums, or -1 if it does not appear. Your algorithm should run in O(log n) time.

Example 1
Input: nums = [-4,-1,2,7,10,15], target = 7
Output: 3

Explanation: nums[3] is 7.

Example 2
Input: nums = [1,3,5,8], target = 4
Output: -1

Explanation: 4 would sit between 3 and 5, but it is not in the array.

Example 3
Input: nums = [6], target = 6
Output: 0

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All values in nums are distinct
  • nums is sorted in ascending order
💡 Hint 1

Look at the middle element. If it is too small, can the target be anywhere to its left?

💡 Hint 2

Keep a window [lo, hi] that must contain the target if it exists, and halve it on every step.

💡 Hint 3

Stop when the window becomes empty (lo > hi); that means the target is absent.

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
function search(nums, target) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc