Facebook PixelBinary Search — Coding Practice
Binary SearchEasy

Binary Search

Easy 12.7k58% acceptance
ArrayBinary Search

Given a sorted array of distinct integers nums and a target, return the index of target if it exists, otherwise -1. Your algorithm must run in O(log n) time.

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 in ascending order with distinct values.
Asked atGoogleMicrosoftApple
JavaScript
Loading editor…
Case 1
[-1,0,3,5,9,12], 9
expected: 4
Case 2
[-1,0,3,5,9,12], 2
expected: -1
Case 3
[5], 5
expected: 0
Case 4
[2,5], 0
expected: -1