Binary Search

Problem

Find the index of a target in a sorted array, or -1 if absent.

Examples

Example 1
Input: {"nums":[1,3,5,7,9],"target":7}
Output: 3
Example 2
Input: {"nums":[1,3,5],"target":6}
Output: -1

Input and output use JSON-compatible values. For linked-list and tree questions, arrays represent the node structure as described above. Your code should implement solve(input).

Write your solutionImplement solve(input). Your draft is saved in this browser.
Advertisement

How to solve Binary Search

Find the index of a target in a sorted array, or -1 if absent. Half the remaining search interval after each comparison. The reference implementation illustrates this approach; check the example and edge cases.

Time and space complexity

O(log n) time and O(1) space.

Practise and improve

Choose JavaScript, TypeScript or Python, complete the starter code, then select Run Tests. Request a hint when you need guidance, or choose View solution and confirm if you would like to study the reference implementation.