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:
- Integer overflow;
mid+1or-1;<=or<inwhile;
Two different styles:
[]or[).The two most commonly used scenarios are "searching for the left boundary" and "searching for the right boundary";
🛠️ 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 ...; }
