Skip to main content

๐Ÿ” Binary Search

Conceptโ€‹

Binary Search repeatedly halves the search space by comparing the target to the middle element. It achieves O(log n) time on sorted data.

Beyond searching for a value, binary search can be applied to answer spaces โ€” searching for a number that satisfies a condition (e.g., "minimum capacity", "k-th smallest").


When to Useโ€‹

  • Array is sorted (or rotated sorted)
  • The problem asks for "minimum X such that condition holds" or "maximum X"
  • Searching in an implicit sorted space (rope cutting, ship capacity, etc.)
  • Finding boundaries (first occurrence, last occurrence)

Java Templateโ€‹

Classic: Find exact targetโ€‹

public int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // avoids overflow vs (left+right)/2
if (nums[mid] == target) return mid;
else if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1; // not found
}

Find left boundary (first occurrence / leftmost valid)โ€‹

public int leftBound(int[] nums, int target) {
int left = 0, right = nums.length;
while (left < right) { // Note: right = length (exclusive)
int mid = left + (right - left) / 2;
if (nums[mid] < target) left = mid + 1;
else right = mid; // do NOT do mid-1; we keep narrowing right
}
return left; // first index where nums[index] >= target
}

Find right boundary (last occurrence)โ€‹

public int rightBound(int[] nums, int target) {
int left = 0, right = nums.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) left = mid + 1;
else right = mid;
}
return left - 1; // last index where nums[index] <= target
}

Binary Search on Answer Spaceโ€‹

// Template: find MINIMUM value x such that feasible(x) is true
public int binarySearchAnswer(int lo, int hi) {
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (feasible(mid)) hi = mid; // mid might be the answer, keep it
else lo = mid + 1;
}
return lo;
}

// feasible() implements the monotonic condition check

Worked Example 1: Search in Rotated Sorted Arrayโ€‹

public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;

// Left half is sorted
if (nums[left] <= nums[mid]) {
if (nums[left] <= target && target < nums[mid]) right = mid - 1;
else left = mid + 1;
} else { // Right half is sorted
if (nums[mid] < target && target <= nums[right]) left = mid + 1;
else right = mid - 1;
}
}
return -1;
}

Worked Example 2: Minimum Capacity to Ship Packages in D Daysโ€‹

Problem: Given weights[], find minimum ship capacity to ship all packages within days days.

public int shipWithinDays(int[] weights, int days) {
// Minimum capacity = max single weight (must fit largest package)
// Maximum capacity = total sum (ship everything in 1 day)
int lo = Arrays.stream(weights).max().getAsInt();
int hi = Arrays.stream(weights).sum();

while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (canShip(weights, days, mid)) hi = mid; // mid works, try smaller
else lo = mid + 1;
}
return lo;
}

private boolean canShip(int[] weights, int days, int capacity) {
int daysNeeded = 1, load = 0;
for (int w : weights) {
if (load + w > capacity) {
daysNeeded++;
load = 0;
}
load += w;
}
return daysNeeded <= days;
}

Time: O(n log(sum)) | Space: O(1)


LeetCode Problemsโ€‹

๐ŸŸข Easyโ€‹

#ProblemVariant
35Search Insert PositionLeft bound
69Sqrt(x)Answer space
278First Bad VersionLeft bound
374Guess Number Higher or LowerClassic
704Binary SearchClassic

๐ŸŸก Mediumโ€‹

#ProblemVariant
33Search in Rotated Sorted ArrayRotated
34Find First and Last PositionLeft + Right bound
153Find Minimum in Rotated Sorted ArrayRotated
162Find Peak ElementSlope climbing
540Single Element in Sorted ArrayParity check
875Koko Eating BananasAnswer space
1011Capacity To Ship PackagesAnswer space

๐Ÿ”ด Hardโ€‹

#ProblemVariant
4Median of Two Sorted ArraysPartition
410Split Array Largest SumAnswer space
668Kth Smallest Number in Multiplication TableAnswer space