Binary Search
EasyGiven a sorted array of integers nums and a target value, return the index of target if it is in nums, otherwise return -1. You must write an algorithm with O(log n) runtime complexity.
Examples
| Input | Output |
|---|---|
| nums = [-1,0,3,5,9,12], target = 9 | 4 |
| nums = [-1,0,3,5,9,12], target = 2 | -1 |
Python Solution
def binary_search(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1JavaScript Solution
function binarySearch(nums, target) {
let left = 0, right = nums.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (nums[mid] === target) return mid;
if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}Step-by-Step Explanation
- Maintain left and right boundaries of the search space.
- Compute mid index and compare with target.
- If equal, return mid. If target is larger, search right half; else search left half.
- Repeat until left > right, then return -1.
Complexity Analysis
| Time | O(log n) |
| Space | O(1) |
Tags
ArrayBinary Search
Related Problems
Related Tools
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix