← Back to DSA
#704
Binary Search
Binary Search solution for LeetCode 704, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Binary Search
Why it belongs on this sheet
This is the base template. If you cannot write this quickly and confidently, the later binary-search problems become much harder.
Pattern
Half-interval elimination
Approach
Maintain left and right pointers. Compare the midpoint with the target and discard the half that cannot contain the answer.
Java solution
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
Complexity
- Time:
O(log n) - Space:
O(1)
Interview note
Always know your invariant: the answer, if it exists, stays inside [left, right].
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)