Binary Search
Core idea
Section titled “Core idea”Every binary search is really: “find the first index where condition becomes true.” If you think of it that way, you only need one template and you never have to remember < vs <=.
Template: first true (lower bound)
Section titled “Template: first true (lower bound)”// Returns the first index in [lo, hi] where ok(mid) is true.// If nothing is true, returns hi (so set hi one past the last valid index if needed).int lo = 0, hi = n; // search space [lo, hi)while (lo < hi) { int mid = lo + (hi - lo) / 2; // avoids int overflow if (ok(mid)) hi = mid; // mid could be the answer, keep it else lo = mid + 1; // mid is definitely not it}return lo;Why lo + (hi - lo) / 2? Because (lo + hi) can overflow when both are close to Integer.MAX_VALUE. Mention this, because interviewers like it.
Talking points:
- “My invariant: everything before
lois false, and everything fromhion is true.” - “The loop ends when lo == hi, which is the first true.”
Problems
Section titled “Problems”Problem: Binary Search (Easy) — LC 704
Approach (say out loud): “Classic search. I’ll use the closed interval [lo, hi] with lo <= hi, and return as soon as I find the target.”
Java:
class Solution { public int search(int[] nums, int target) { int lo = 0, hi = nums.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] == target) return mid; if (nums[mid] < target) lo = mid + 1; else hi = mid - 1; } return -1; }}Complexity: O(log n) time, O(1) space
Edge cases: a single element, target smaller or bigger than every element.
Problem: Find First and Last Position of Element in Sorted Array (Medium) — LC 34
Approach (say out loud): “Two lower-bound searches. First = first index with nums[i] >= target. Last = (first index with nums[i] >= target + 1) - 1. If first is out of range or isn’t the target, return [-1, -1].”
Java:
class Solution { public int[] searchRange(int[] nums, int target) { int first = lowerBound(nums, target); if (first == nums.length || nums[first] != target) return new int[]{-1, -1}; int last = lowerBound(nums, target + 1) - 1; return new int[]{first, last}; }
// first index i with nums[i] >= target private int lowerBound(int[] nums, int target) { int lo = 0, hi = nums.length; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] >= target) hi = mid; else lo = mid + 1; } return lo; }}Complexity: O(log n) time, O(1) space
Edge cases: empty array, target missing, all elements equal to the target. (target + 1 could overflow at Integer.MAX_VALUE. Mention it, or write a separate upper-bound function using >.)
Problem: Search Insert Position (Easy) — LC 35
Approach (say out loud): “This is exactly lower bound: the first index where nums[i] >= target.”
Java:
class Solution { public int searchInsert(int[] nums, int target) { int lo = 0, hi = nums.length; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] >= target) hi = mid; else lo = mid + 1; } return lo; }}Complexity: O(log n) time, O(1) space
Edge cases: target bigger than all → n, smaller than all → 0.
Problem: Koko Eating Bananas (Medium) — LC 875
Approach (say out loud): “I binary search on the speed k, not on the array. The speed is between 1 and max(piles). If Koko can finish at speed k, she can finish at any faster speed, so it’s monotonic. I find the smallest k where hours ≤ h. Hours for a pile = ceil(pile / k) = (pile + k - 1) / k.”
Java:
class Solution { public int minEatingSpeed(int[] piles, int h) { int lo = 1, hi = 0; for (int p : piles) hi = Math.max(hi, p); while (lo < hi) { int mid = lo + (hi - lo) / 2; if (canFinish(piles, h, mid)) hi = mid; else lo = mid + 1; } return lo; }
private boolean canFinish(int[] piles, int h, int k) { long hours = 0; // long: the sum can overflow int for (int p : piles) hours += (p + k - 1) / k; return hours <= h; }}Complexity: O(n log M) time, where M = max pile. O(1) space.
Edge cases: h == piles.length (the answer is max pile), very large piles (use long for hours). Note that p + k - 1 stays within int here because both are at most about 10^9.
Problem: Find Minimum in Rotated Sorted Array (Medium) — LC 153
Approach (say out loud): “Compare mid with the rightmost element. If nums[mid] > nums[hi], the drop (the minimum) is to the right of mid. Otherwise the minimum is at mid or to its left.”
Java:
class Solution { public int findMin(int[] nums) { int lo = 0, hi = nums.length - 1; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] > nums[hi]) lo = mid + 1; else hi = mid; } return nums[lo]; }}Complexity: O(log n) time, O(1) space
Edge cases: not rotated at all, a single element, two elements.
Problem: Search in Rotated Sorted Array (Medium) — LC 33
Approach (say out loud): “At any mid, at least one half is sorted. I check which half is sorted, then check whether the target lies inside that sorted half’s range. If it does, I search there. Otherwise I search the other half.”
Java:
class Solution { public int search(int[] nums, int target) { int lo = 0, hi = nums.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] == target) return mid;
if (nums[lo] <= nums[mid]) { // left half sorted if (nums[lo] <= target && target < nums[mid]) hi = mid - 1; else lo = mid + 1; } else { // right half sorted if (nums[mid] < target && target <= nums[hi]) lo = mid + 1; else hi = mid - 1; } } return -1; }}Complexity: O(log n) time, O(1) space
Edge cases: nums[lo] <= nums[mid] needs the = for when lo == mid (two elements left), the target is missing, the array isn’t rotated.
Problem: Search a 2D Matrix (Medium) — LC 74
Approach (say out loud): “Rows are sorted, and each row starts after the previous row ends, so it’s one sorted array of size m·n. I binary search over index i and map it to matrix[i / n][i % n].”
Java:
class Solution { public boolean searchMatrix(int[][] matrix, int target) { int m = matrix.length, n = matrix[0].length; int lo = 0, hi = m * n - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; int val = matrix[mid / n][mid % n]; if (val == target) return true; if (val < target) lo = mid + 1; else hi = mid - 1; } return false; }}Complexity: O(log(m·n)) time, O(1) space
Edge cases: a 1×1 matrix, a single row, a single column.