Stage 1 · Code
Stack & Binary Search
Classic Binary Search
Master the lo/hi/mid invariants once and solve every binary search variant without off-by-one bugs.
8 min readLeetCode Patterns for InterviewsCode
The Pattern
Binary search halves the search space each step. The key is maintaining the invariant: the answer is always within [lo, hi]. Use lo=0, hi=n-1 for exact search; lo=0, hi=n for 'first/last position' search.
Binary search — lo=0, hi=6, mid=3 highlights the middle element
1lo=0
3
5
7mid=3
9
11
13hi=6
0
1
2
3
4
5
6
Gothree-binary-search-templates.go
41 linesLn 1, Col 1Go
Use lo+(hi-lo)/2 to avoid integer overflow. The three templates cover: exact search, first position ≥ target, and last position ≤ target.
Problems
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.