β All problems
#704Easyπ Pattern ???
Binary Search
Given an array sorted in ascending order and a target, return the target's index or -1 if it is missing. It must run in O(log n).
Try it on LeetCodeπ€ GUESS THE PATTERN+5 XP
Before you peek at the solution: which pattern do you think this one uses?
Hints0/3
Optional. Open them one at a time if you're stuck.
π¬ Walkthrough video

Video coming soon
The video is still being edited. Meanwhile, read the explanation and the code.
π Explanation
Intuition
Because the array is sorted, one comparison with the middle element tells you whether the target lives in the left half or the right half. The other half is thrown away.
Each step halves the search space, so it takes at most logβ n steps. For a million elements, that is only about 20 steps.
Steps
lo = 0,hi = n - 1(a closed range).- While
lo <= hi:mid = lo + (hi - lo) / 2(overflow-safe).- If
nums[mid] == target, returnmid. - If
nums[mid] < target,lo = mid + 1. - Otherwise
hi = mid - 1.
- Return
-1.
Traps
- Use
lo <= hi, not<. Otherwise a one-element range gets skipped. - Always move to
mid Β± 1so the loop can't get stuck.
β±οΈ Complexity
TimeO(log n)
SpaceO(1)
π» Solution code
class Solution:
def search(self, nums: list[int], target: int) -> int:
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Got it and submitted?
Mark it solved to earn XP and keep your streak alive.