๐๏ธ Day 15: Binary Search on Answers
๐ง Concept Deep Dive
What if we don't search in an array, but in a range of values to find the answer?
This is called Binary Search on the Answer โ often used when:
- You need to minimize or maximize a condition
- You can check feasibility of a solution efficiently
Itโs often combined with a helper function like canDo(mid).
๐ ๏ธ Pattern
- Define the search space:
lowandhigh - While
low < high, do:- Compute
mid = Math.floor((low + high) / 2) - If condition is true at
mid, updatehigh = mid - Else, update
low = mid + 1
- Compute
- Return
low(orhigh, depending)
๐ก Example Problem: Minimum Pages Allocation
๐งฉ Problem:
Given n books with pages[i] and m students, allocate books such that:
- Each student gets contiguous books
- Max pages assigned to a student is minimized
โจ Goal:
Minimize the maximum pages assigned to a student.
โ Helper Function: isFeasible
function isFeasible(pages: number[], students: number, maxPages: number): boolean {
let count = 1, total = 0;
for (const page of pages) {
if (page > maxPages) return false;
if (total + page > maxPages) {
count++;
total = page;
} else {
total += page;
}
}
return count <= students;
}๐ Binary Search on Answer
function findMinimumPages(pages: number[], students: number): number {
let low = Math.max(...pages);
let high = pages.reduce((a, b) => a + b);
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (isFeasible(pages, students, mid)) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}๐งช Example
Input: pages = [10, 20, 30, 40], students = 2
Output: 60
Explanation: Allocate [10, 20, 30] and [40]๐ Big O Complexity
| Operation | Time | Space |
|---|---|---|
| Binary Search on Range | O(n log sum) | O(1) |
Where n = number of books, sum = total pages
๐ง Real-world Analogy
Imagine you're assigning chapters to friends to summarize for a book club. You want to distribute the chapters so no one gets too much work. You try different maximum workloads (mid), and see if it's feasible to assign them within the given number of people.
๐งช LeetCode-style Homework
Problem: Capacity To Ship Packages Within D Days
function shipWithinDays(weights: number[], days: number): number {
let low = Math.max(...weights);
let high = weights.reduce((a, b) => a + b);
const canShip = (capacity: number): boolean => {
let day = 1, load = 0;
for (const w of weights) {
if (load + w > capacity) {
day++;
load = w;
} else {
load += w;
}
}
return day <= days;
};
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (canShip(mid)) high = mid;
else low = mid + 1;
}
return low;
}๐ Summary
- Binary search isnโt just for arrays!
- Use it to find min/max feasible answers
- Needs a helper function to check feasibility
๐ฎ Up Next
โถ๏ธ Day 16: Two Pointers Technique