This problem follows the Classic Binary Search pattern, commonly found in the Binary Search category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Compare target with mid. Narrow to left or right half accordingly.
The key is the loop invariant: the target, if it exists, is always in [left, right]. Each iteration halves this range.
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1Practice Binary Search and similar Binary Search problems with flashcards. Build pattern recognition through active recall.
Practice this problem