Searching
Find a target - linearly on any data, or in O(log n) when it’s sorted.
- inside the window
- ruled out
- active this step
- result
Search the whole array
lo = 0 and hi = 8 cover all 9 values.
VARIABLES
- lo
- 0
- hi
- 8
- mid
- -
- nums[mid]
- -
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Linear search checks every element. Binary search halves a sorted range at each step by comparing the middle element with the target.
Why it matters
Halving turns a scan of a million elements into about 20 comparisons.
Think of it like this
Guessing a number from 1 to 100 by always guessing the middle: you never need more than 7 guesses.
Use it when
- The data is sorted, or a condition is monotonic
- You need the first or last position meeting a condition
- Repeated lookups on data that doesn’t change
Avoid it when
- Unsorted data you search only once - a linear scan is simpler
- Frequent inserts - keeping the array sorted costs O(n) each
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Linear search | O(n) | O(1) |
| Binary search | O(log n) | O(1) |
| Hash set lookup | O(1) average | O(n) |
Often confused with: two pointers - also uses sorted order, but moves one step at a time, so it’s O(n).
How to recognize it
Clues in interview prompts that point straight to this pattern.
- A required O(log n) runtime almost always means binary search
- An answer range up to 10⁹ hints at searching the answer space
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Writing while lo < hi with hi = mid − 1 - the last candidate is never checked
- Setting lo = mid instead of mid + 1 - an infinite loop
- Forgetting that the array must be sorted
Edge cases to test
- Empty array - return -1 right away
- Target smaller or larger than every value
- Duplicates - decide whether you want the first or last match
Knowledge check
Quick check to lock in the intuition.
About how many comparisons does binary search need for 1,000,000 sorted items in the worst case?
Practice
Apply what you just watched on real interview problems.