Skip to interview prep
Apexed

8. Binary Search

EasyBinary search

Given a sorted array of distinct integers nums and a target, return the index of target, or -1 if it is not present. Aim for O(log n).

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

Constraints

  • 1 ≤ nums.length ≤ 10⁴
  • nums is sorted ascending

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 6 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Binary Search — coding interview practice — Apexed