Problem
Given a sorted array of integers and a target value, return the index of the target. If the target is not found, return -1. The catch: you must achieve O(log n) runtime, which means you can't just scan every element.
- Input:
nums = [-1, 0, 3, 5, 9, 12],target = 9 - Output:
4 - Explanation: 9 is at index 4 in the array.
Counter-example: target = 2 โ return -1 because 2 does not appear anywhere in the array.
Intuition
Because the array is sorted, any element splits it into two halves where everything on the left is smaller and everything on the right is larger. If the middle element isn't the target, you can throw away the wrong half entirely. Each comparison cuts the search space in half, turning O(n) work into O(log n).
Approach 1 โ Linear Scan
Iterate through every element until you find the target. This works but ignores the sorted order entirely โ every element is visited even if the target could never appear in the remaining half.
- Walk through the array from left to right.
- At each position, compare the current value to the target.
- Return the index on a match.
- Return -1 if the loop finishes without finding the target.
1def search(nums: list[int], target: int) -> int:
2 for index, value in enumerate(nums):
3 if value == target:
4 return index
5 if value > target: # sorted array โ target can't appear further right
6 break
7 return -1Time: O(n) โ in the worst case (target not in array), every element is visited.
Space: O(1) โ no extra memory beyond the loop variable.
Approach 2 โ Binary Search
Maintain a search window with left and right pointers. At each step, check the middle element and shrink the window toward whichever half could contain the target.
- Initialize
left = 0andright = len(nums) - 1. - While the window is non-empty (
left <= right), computemid = left + (right - left) // 2. - If
nums[mid] == target, returnmid. - If
nums[mid] < target, the target must be in the right half โ setleft = mid + 1. - If
nums[mid] > target, the target must be in the left half โ setright = mid - 1. - If the window collapses without a match, return -1.
1def search(nums: list[int], target: int) -> int:
2 left, right = 0, len(nums) - 1
3
4 while left <= right:
5 mid = left + (right - left) // 2 # avoids overflow in languages with fixed int width
6
7 if nums[mid] == target:
8 return mid
9 elif nums[mid] < target:
10 left = mid + 1 # target is somewhere to the right
11 else:
12 right = mid - 1 # target is somewhere to the left
13
14 return -1Time: O(log n) โ the search window halves on every iteration.
Space: O(1) โ only two pointers and a midpoint variable.
Complexity Summary
| Approach | Time | Space | When to use |
|---|---|---|---|
| Linear Scan | O(n) | O(1) | Unsorted arrays, or as a fallback when sorting is not guaranteed |
| Binary Search | O(log n) | O(1) | Any sorted array โ the standard approach for all interview questions involving sorted data |
Common Mistakes
-
Using
left < rightinstead ofleft <= rightโ the<condition exits the loop when one element remains, causing that element to never be checked. The target could be that single element, so you need<=. -
Writing
mid = (left + right) / 2โ this overflows in Java and C++ when both pointers are nearINT_MAX. The safe form isleft + (right - left) / 2, which produces the same midpoint without risk of overflow. -
Forgetting the
+ 1or- 1shift โ writingleft = midinstead ofleft = mid + 1(orright = midinstead ofright = mid - 1) causes an infinite loop whenleft == right, becausemidequalsleftand the window never shrinks. -
Moving the wrong pointer โ after ruling out the middle element, the new boundary should exclude it. If
nums[mid] < target, you knowmidis not the answer, so setleft = mid + 1, notleft = mid. -
Returning the wrong value when not found โ some implementations return
left(which would give the insertion point, useful for other problems) when the loop ends. For this problem, the contract is to return -1 on a miss.
Related Problems
find-first-and-last-position-of-element-in-sorted-arrayโ two binary searches to find the leftmost and rightmost occurrencesearch-in-rotated-sorted-arrayโ binary search adapted for an array that has been rotated at some pivotfind-minimum-in-rotated-sorted-arrayโ binary search to locate the inflection point in a rotated sorted arraykoko-eating-bananasโ binary search over an answer space rather than a value in an arraycapacity-to-ship-packages-within-d-daysโ same "binary search on the answer" pattern applied to a capacity constraint