Binary Search – Solution & Complexity
1. Understand the Sorted Input
- The array is sorted in ascending order.
- You need return the index of
target, or-1if it is missing. - The requested O(log n) time means we should repeatedly discard half of the search range.
2. Why Linear Search Is Not Enough
- Checking each element from left to right is simple and correct.
- However, it can inspect every value in the worst case.
- That makes it O(n), which does not meet the requirement.
3. Use the Middle Element
- Binary search keeps two pointers:
leftandright. - Look at the middle index between them.
- If the middle value is too small, search the right half; if it is too large, search the left half.
4. Update the Search Bounds
- When
nums[mid] < target, all values atmidand left of it are too small, so movelefttomid + 1. - When
nums[mid] > target, all values atmidand right of it are too large, so moverighttomid - 1. - Stop when the bounds cross.
5. Final Solution and Complexity
- The equality check returns immediately when the target is found.
- Each loop removes about half of the remaining values.
- Time complexity is O(log n), and space complexity is O(1).