Continue learning
Practice related DSA questions in the same topic.
Find the target in a sorted array. Return any matching zero-based index, or -1.
Find the target in a sorted array. Return any matching zero-based index, or -1.
def solve(values, target): left = 0 right = (len(values) - 1) while (left <= right): mid = (left + ((right - left) // 2)) if (values[mid] == target): return mid if (values[mid] < target): left = (mid + 1) else: right = (mid - 1) return -1Inspect midpoint 4 within the remaining bounds.
Inspect midpoint 4 within the remaining bounds.
A librarian opens the middle of a sorted catalogue and closes an entire half after each comparison.
Check the midpoint of the inclusive range. Sorted order tells you which half cannot contain the target.
O(log n) time · O(1) auxiliary space
Worked example · {"values":[2,5,8,12,16,23,38,56,72],"target":23} ⇒ 5
Edge case 1 · {"values":[],"target":3} ⇒ -1
Edge case 2 · {"values":[2],"target":3} ⇒ -1
Edge case 3 · {"values":[4],"target":4} ⇒ 0
Updating a boundary to mid instead of moving past it can repeat the same interval forever.
How would the boundaries change if you needed the first match?