← 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

  1. lo = 0, hi = n - 1 (a closed range).
  2. While lo <= hi:
    • mid = lo + (hi - lo) / 2 (overflow-safe).
    • If nums[mid] == target, return mid.
    • If nums[mid] < target, lo = mid + 1.
    • Otherwise hi = mid - 1.
  3. Return -1.

Traps

  • Use lo <= hi, not <. Otherwise a one-element range gets skipped.
  • Always move to mid Β± 1 so 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 -1

Got it and submitted?

Mark it solved to earn XP and keep your streak alive.