Binary Search
Find a target's index in a sorted array in O(log n) by halving the search range at every step.
The problem
You get an array nums of distinct integers sorted in increasing order, and an integer target. Return the index of target in nums, or -1 if it is not there. Your solution must run in O(log n) time.
Input nums = [-7, -2, 0, 5, 9, 14], target = 9
Output 4
9 sits at index 4.
Input nums = [1, 3, 8, 11], target = 4
Output -1
4 would belong between 3 and 8, but it isn't in the array.
How to spot the pattern
- The array is sorted and you are looking for one value.
- The required time is O(log n), which a scan from left to right can't meet.
The idea
Compare target with the middle element of the range you are still searching. If they are equal you are done; if the middle is smaller, the target can only be in the right half, and if it is bigger, only in the left half. Each comparison throws away half of the remaining range, so about log2(n) steps are enough.
Brute force: Scan the array from left to right, which takes O(n) time.
Step by step
- 1Set
lo = 0andhi = n - 1. - 2While
lo <= hi, computemid = lo + (hi - lo) / 2with integer division. - 3If
nums[mid]equalstarget, returnmid. - 4If
nums[mid] < target, setlo = mid + 1; otherwise sethi = mid - 1. - 5If the loop ends, the target is missing, so return -1.
See the pattern move
The binary search pattern on a small example. Step through it, or press play.
Code
class Solution:
def search(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1 # the target can only be on the right
else:
hi = mid - 1 # the target can only be on the left
return -1Complexity
Time
O(log n)
Space
O(1)
Each step halves the range, so an array of 10,000 numbers needs at most 14 comparisons.
Watch out for
- Writing
while lo < hiin this version, which stops before checking the last remaining element. - Setting
lo = midorhi = midinstead ofmid + 1andmid - 1, which can loop forever on a range of two elements. - Computing
(lo + hi) / 2in Java or C++ on a huge array, where the sum can overflow;lo + (hi - lo) / 2never does.
Follow-up questions
What if the array can contain duplicates and you need the first copy?
Don't stop at a match: remember it and keep searching the left half. That is the lower bound search used in Find First and Last Position of Element in Sorted Array.
What if the target is missing and you need the index where it would go?
When the loop ends, lo is that index: the first position whose value is bigger than the target. That is Search Insert Position.
In Hinglish
Beech wala element dekho; target bada hai toh right half mein jao, chhota hai toh left half mein. Har step mein aadha kaam khatam.