Binary Search Concept & Pattern
Original1/30/26Less than 1 minute
Problem Domain
First, you need to abstract an independent variable , a function of , and a target value from the problem.
Additionally, , , and must satisfy the following conditions:
must be a monotonic function on (monotonically increasing or monotonically decreasing is acceptable).
The problem asks you to calculate the value of when the constraint is satisfied.
🧠 Concept
Idea is simple: divide and conquer.
- By shrinking (halving) the search space as much as possible using known information, we can increase the efficiency of exhaustive search and quickly find the target.
Details are important:
- My preference:
[]; - Integer overflow:
left + (right - left) / 2instead of(left + right) / 2; - Out of boundary problem: When you calculate
mid, should you add 1 or not, which means when there are two elements in the search range, shouldmidsit at left or right; <=or<inwhile;
- My preference:
One hint for binary search, which is easy to overlook, is that we know the range of the result and we are trying to find a min or max value within that range that validates some conditions at the same time.
🛠️ Algorithm
int binarySearch(int[] nums, int target) { int left = 0, right = ...; while(...) { int mid = left + (right - left) / 2; if (nums[mid] == target) { ... } else if (nums[mid] < target) { left = ... } else if (nums[mid] > target) { right = ... } } return ...; }
