Problems

Binary Search

easy
easy
arrays
binary-search

Given an ascending array of distinct integers, return the index of target or -1 when it is absent.

Input / output

  • Input: nums: integer[], target: integer
  • Output: zero-based integer index

Examples

  1. nums = [-1,0,3,5,9,12], target = 9 returns 4.
  2. The same array with target = 2 returns -1.

Constraints

  • 0 <= nums.length <= 100,000
  • Values are strictly increasing

Follow-up Explain the loop invariant and how you avoid midpoint overflow in fixed-width integer languages.

Examples

Example 1

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

Example 2

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

Example 3

Input: nums = [5], target = 5
Output: 0
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.