Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Binary Search

Searchingeasy

Given a sorted ascending array `nums`, implement `search(nums, target)` returning the index of `target`, or `-1` if absent.

Sample tests

Input: search([-1,0,3,5,9,12], 9)
Output: 4
Input: search([-1,0,3,5,9,12], 2)
Output: -1

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • An inclusive/exclusive bound mistake causes an infinite loop or missed element.

Learning resources

  • Wikipedia: Binary search
Approach & explanation (try first)

Binary search halves the range each step. O(log n) time, O(1) space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.