NeetCode 150 / Binary Search
EasyBinary SearchO(log n)

Dry run

nums = [-1, 0, 3, 5, 9, 12] · target = 9Step 1 of 5
-1
0lo
0
1
3
2
5
3
9
4
12
5hi
target
9

Point lo at the first cell and hi at the last. The answer, if it exists, sits somewhere inside this window.

Pythontime O(log n) · space O(1)
1def search(nums, target):
2 lo, hi = 0, len(nums) - 1
3 while lo <= hi:
4 mid = (lo + hi) // 2
5 if nums[mid] == target:
6 return mid
7 elif nums[mid] < target:
8 lo = mid + 1
9 else:
10 hi = mid - 1
11 return -1
Variables
lo0
hi5
mid—
nums[mid]—

Problem

Given an array of integers nums sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity.

Examples

Input: nums = [-1,0,3,5,9,12], target = 9Output: 4

9 exists at index 4

Input: nums = [-1,0,3,5,9,12], target = 2Output: -1

2 does not exist

Constraints

  • 1 ≤ nums.length ≤ 10⁴
  • All integers are unique
  • nums is sorted ascending

Intuition

Because the array is sorted, comparing the target with the middle element tells us which half the target must be in. Discard the other half and repeat on what remains — the window halves every step, so we need about log₂ n comparisons.

Brute force → Optimal

Brute force

Walk every element from left to right and return the index where it equals the target; return -1 if the scan ends.

Time O(n)Space O(1)
Optimal

Keep a window [lo, hi]. Look at mid = (lo + hi) / 2. If nums[mid] is the target, return mid; if it is smaller, the answer is to the right, so lo = mid + 1; otherwise hi = mid - 1. Stop when lo > hi.

Time O(log n)Space O(1)

Complexity

Time O(log n)Space O(1)

Edge cases

  • Target smaller than the first element or larger than the last: the window collapses after a few halvings and the loop returns -1.
  • A single-element array: the only middle is index 0, so the target is found immediately or not at all.

Common mistakes

  • Using `while (lo < hi)` instead of `while (lo <= hi)`, which skips the final one-element window and can miss the target.
  • Setting lo = mid instead of lo = mid + 1 when nums[mid] is too small, which can loop forever on a two-element window.

জটিলতা

O(log n)
সময় — অ্যারেটা একবারই ঘুরি, ম্যাপে খোঁজা O(1)।
O(1)
জায়গা — সবচেয়ে খারাপ ক্ষেত্রে সব সংখ্যা ম্যাপে থাকে।
আগের সমস্যা← Largest Rectangle in Histogramপরের সমস্যাSearch a 2D Matrix →