Binary Search

Easy#704find a number

You get an array of distinct numbers sorted in increasing order and a target number. Return the index of the target, or −1 if it is not in the array, in O(log n) time. Our example: [-4, 0, 3, 9, 14, 20, 27] and 15 — the answer is −1: 15 would stand between 14 and 20, but it is not there.

input
nums: different integers in ascending order; target: an integer.
returns
The index of target in nums, or -1 if it is not there. LeetCode wants it in O(log n).
constraints
  • 1 ≤ nums.length ≤ 10⁴
  • −10⁴ < nums[i], target < 10⁴
  • nums is in ascending order, all different
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
function search(nums, target) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more binary search problems

Pattern “Binary search” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.