CodeSpeek

Binary Search

Easy · Binary Search

You are given an array of integers sorted in ascending order with no duplicates, and a target value. Return the index of the target in the array if it exists, otherwise return -1. Your approach should take advantage of the sorted order rather than scanning every element.

Examples

Input:  nums = [-1,0,3,5,9,12], target = 9
Output: 4
Why:    9 appears at index 4 in the array.
Input:  nums = [-1,0,3,5,9,12], target = 2
Output: -1
Why:    2 is not present in the array.
Input:  nums = [5], target = 5
Output: 0
Why:    The single element equals the target, found at index 0.

Constraints

1 <= nums.length <= 10^4, -10^4 <= nums[i], target <= 10^4, nums is sorted ascending with all distinct values

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Binary Search

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Binary Search. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.