- Link: 704. Binary Search - Easy
- Track: NeetCode150
Question
Restate the problem
- Given a sorted array
numsand atarget, return its index. Return-1if not found.
Edge Case
- Empty array → return
-1 - Target smaller than
nums[0]or larger thannums[-1]→ return-1
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Binary Search |
Method 1 - Binary Search
Approach
Key Insight
Sorted array → each step, compare
nums[mid]totargetand eliminate half the remaining search space.
nums[mid] < target→ target is in right half →left = mid + 1nums[mid] > target→ target is in left half →right = mid - 1
Step-by-step:
- Set
left = 0,right = len(nums) - 1. - While
left <= right:- Compute
mid = left + (right - left) // 2 - If
nums[mid] == target→ returnmid - If
nums[mid] < target→left = mid + 1 - Else →
right = mid - 1
- Compute
- Return
-1.
Complexity
- Time Complexity:
- Space Complexity:
Code
class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1Mistake
left < rightinstead ofleft <= right: misses the case where the answer is the single remaining element.right = midinstead ofright = mid - 1: causes infinite loop whenleft == mid.mid = (left + right) // 2: integer overflow in other languages; preferleft + (right - left) // 2.