Practice: binary search
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Binary search problems fall into three families: boundary queries on sorted arrays (lowerBound / upperBound), structural binary search on rotated arrays and peaks, and binary search on the answer for optimization and roots. Before solving the six mixed practice problems below, lock in the universal off-by-one checklist.
Search insert position and count of occurrences
Two small functions, lowerBound and upperBound, solve four problems with one 7-line template.
int[] nums = {1, 2, 2, 2, 5};int insertAt = lowerBound(nums, 3); // 4: Search Insert Positionint count = upperBound(nums, 2) - lowerBound(nums, 2); // 4 - 1 = 3 copies of 2int inRange = upperBound(nums, 5) - lowerBound(nums, 2); // 5 - 1 = 4 values in [2, 5]lowerBound(nums, target) is the first index i in 0 .. n with nums[i] >= target; upperBound(nums, target) is the first index with nums[i] > target:
- Search Insert Position:
lowerBound(nums, target). - First and Last Position:
[lowerBound(nums, x), upperBound(nums, x) - 1](whenlb < n && nums[lb] == x). - Count of Occurrences:
upperBound(nums, x) - lowerBound(nums, x). - Range Count in
[L, R]:upperBound(nums, R) - lowerBound(nums, L).
Find minimum in a rotated array with duplicates
In Find Minimum in Rotated Sorted Array II, the rotated sorted array may contain duplicate values (such as [2, 2, 2, 0, 1] or [10, 1, 10, 10, 10]).
Example 1 · Find Minimum in Rotated Sorted Array II with duplicates
public class FindMinRotatedDuplicatesDemo { public static 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 if (nums[mid] < nums[hi]) { hi = mid; } else { hi--; // nums[mid] == nums[hi]: safe to drop hi! } } return nums[lo]; }
public static void main(String[] args) { System.out.println(findMin(new int[]{2, 2, 2, 0, 1})); System.out.println(findMin(new int[]{10, 1, 10, 10, 10})); }}0 1
What this code does
- On [10, 1, 10, 10, 10], lo=0, hi=4, mid=2: nums[2] == nums[4] == 10, so hi-- safely shrinks to [0..3].
- Average case is O(log n), and only in the all-equal worst case does hi-- take O(n) steps.
Comparing nums[mid] with nums[hi] has three cases:
nums[mid] > nums[hi]: the minimum is strictly to the right (lo = mid + 1).nums[mid] < nums[hi]: the minimum is at or to the left ofmid(hi = mid).nums[mid] == nums[hi]: we cannot tell which side the minimum is on, but sincemid < hiandnums[mid]holds a copy ofnums[hi], discardinghiviahi--never loses the minimum value!
Capacity to ship packages and book allocation
In both Capacity To Ship Packages Within D Days and Allocate Minimum Number of Pages (Book Allocation), we partition an array of positive weights/pages arr[] into at most k contiguous groups so that the maximum group sum is minimized.
Example 2 · Book Allocation (Minimize Maximum Pages Assigned to Any Student)
public class BookAllocationDemo { public static int allocateBooks(int[] pages, int students) { if (students > pages.length) return -1; int lo = 0, hi = 0; for (int p : pages) { lo = Math.max(lo, p); hi += p; } while (lo < hi) { int mid = lo + (hi - lo) / 2; int needed = 1, cur = 0; for (int p : pages) { if (cur + p > mid) { needed++; cur = p; } else { cur += p; } } if (needed <= students) hi = mid; else lo = mid + 1; } return lo; }
public static void main(String[] args) { int[] pages = {12, 34, 67, 90}; System.out.println("Min max pages for 2 students: " + allocateBooks(pages, 2)); System.out.println("Min max pages for 5 students: " + allocateBooks(pages, 5)); }}Min max pages for 2 students: 113 Min max pages for 5 students: -1
What this code does
- For 2 students, student 1 gets [12, 34, 67] (113 pages) and student 2 gets [90] (90 pages), giving max = 113.
- For 5 students with only 4 books, it is impossible to give every student at least 1 book, so it returns -1.
- Answer space:
lo = max(arr)(largest single item),hi = sum(arr)(all items in 1 group). - Note on Book Allocation: if the problem additionally requires every one of the
kstudents to receive at least 1 book andk > arr.length, return-1immediately; whenk <= arr.length, any partition into<= kpieces can be split further into exactlyknon-empty pieces without increasing the maximum piece sum!
Nth root of a number
Given positive integers n and m, how do you find the integer n-th root ⌊ m^(1/n) ⌋ (or exact integer x with xⁿ == m, else -1) in O(log m · log n) time?
Example 3 · Overflow-safe Nth root of an integer
public class NthRootDemo { // Returns base^exp capped at limit + 1 so it never overflows long! private static long powerCapped(long base, int exp, long limit) { long result = 1; for (int i = 0; i < exp; i++) { result *= base; if (result > limit) return limit + 1; } return result; }
// Returns exact integer x such that x^n == m, or -1 if none exists public static int exactNthRoot(int n, long m) { long lo = 1, hi = m; while (lo <= hi) { long mid = lo + (hi - lo) / 2; long p = powerCapped(mid, n, m); if (p == m) return (int) mid; if (p < m) lo = mid + 1; else hi = mid - 1; } return -1; }
public static void main(String[] args) { System.out.println("3rd root of 27: " + exactNthRoot(3, 27)); System.out.println("4th root of 69: " + exactNthRoot(4, 69)); System.out.println("6th root of 4096: " + exactNthRoot(6, 4096)); }}3rd root of 27: 3 4th root of 69: -1 6th root of 4096: 4
What this code does
- Because powerCapped stops as soon as result > m (and m <= 10^9), result = base is at most 10^9 10^9 = 10^18, which always fits in a signed 64-bit long!
- This avoids all floating-point rounding issues of Math.pow(m, 1.0 / n).
Binary search mid in [1 .. m]. What is the trap when computing mid^n? If m = 10^9 and n = 30, mid starts at 5 × 10⁸, and Math.pow(mid, 30) is 10²⁶¹, which overflows long! Instead, write a small helper powerCapped(base, exp, limit) that multiplies ans *= base in a loop and stops immediately returning limit + 1 as soon as ans > limit! That completely prevents overflow for any n and m.
An off-by-one checklist for every binary search
Before submitting any binary search, run through this 5-point checklist:
- Safe midpoint: Did I write
lo + (hi - lo) / 2instead of(lo + hi) / 2? - 2-element termination: If
hi == lo + 1, does every branch strictly shrinkhi - lo? (If a branch setslo = midinsidewhile (lo < hi), did I roundmidup vialo + (hi - lo + 1) / 2?) - Inclusive vs half-open bounds: Does
histart atn - 1(all indices valid) orn(lowerBound/upperBoundwherenis a valid insertion answer)? - Overflow inside
canDo(mid): Did I uselongfor running sums (totalHours,currentSum,mid * mid) inside the feasibility helper? - Empty / 1-element / not-found post-check: When
while (lo < hi)finishes atlo == hi, am I guaranteed an answer exists, or do I need a final checkif (lo < n && arr[lo] == target)?
Finish up
Mark complete & continue
Next: Recursion refresher