Binary Search on Answer Technique in DSA Typescript - Time & Space Complexity
We want to understand how fast the binary search on answer technique finds the best solution.
How does the number of steps grow as the range of possible answers grows?
Analyze the time complexity of this binary search on answer code.
function binarySearchOnAnswer(low: number, high: number, check: (mid: number) => boolean): number {
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (check(mid)) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return low;
}
This code tries to find the smallest value that passes the check by narrowing the search range.
Look for loops or repeated steps.
- Primary operation: The while loop that halves the search range each time.
- How many times: About log base 2 of the size of the range (high - low + 1).
Each step cuts the search space in half, so the number of steps grows slowly.
| Input Size (range size) | Approx. Operations (loop iterations) |
|---|---|
| 10 | About 4 |
| 100 | About 7 |
| 1000 | About 10 |
Pattern observation: Doubling the input size adds only one more step.
Time Complexity: O(log n)
This means the steps grow slowly, making it efficient even for large ranges.
[X] Wrong: "The loop runs once for every number in the range, so it is O(n)."
[OK] Correct: Each loop cuts the range in half, so the number of loops grows much slower than the range size.
Understanding this technique shows you can solve problems efficiently by smart searching, a skill valued in many coding challenges.
What if the check function took longer to run? How would that affect the overall time complexity?
Practice
Binary Search on Answer technique?Solution
Step 1: Understand the technique's purpose
Binary Search on Answer guesses a possible answer value and checks if it meets the problem's conditions.Step 2: Adjust guess based on check
If the guess is valid, we try smaller or larger values accordingly to find the optimal answer.Final Answer:
We guess an answer and check if it satisfies the problem constraints, then adjust the guess. -> Option AQuick Check:
Guess and check approach = C [OK]
- Confusing with normal binary search on arrays
- Assuming input must be sorted
- Thinking it divides input recursively
low and high?Solution
Step 1: Identify correct mid calculation
Midpoint must be an integer index, so use Math.floor to avoid decimals.Step 2: Confirm loop condition and syntax
Use while loop with condition low <= high for binary search iteration.Final Answer:
while (low <= high) { let mid = Math.floor((low + high) / 2); } -> Option CQuick Check:
Integer mid with while loop = B [OK]
- Using division without floor causing float mid
- Using for loop instead of while
- Using bitwise shift without understanding
function canShip(weights: number[], capacity: number, D: number): boolean {
let days = 1, total = 0;
for (const w of weights) {
if (total + w > capacity) {
days++;
total = 0;
}
total += w;
}
return days <= D;
}
function shipWithinDays(weights: number[], D: number): number {
let low = Math.max(...weights);
let high = weights.reduce((a, b) => a + b, 0);
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (canShip(weights, mid, D)) high = mid;
else low = mid + 1;
}
return low;
}
console.log(shipWithinDays([1,2,3,4,5,6,7,8,9,10], 5));What is the output?Solution
Step 1: Understand problem and code
We find minimum ship capacity to ship weights in 5 days. Minimum capacity is max weight (10), max capacity is sum (55).Step 2: Trace binary search and canShip checks
Binary search narrows capacity to 15, which allows shipping in 5 days by grouping weights properly.Final Answer:
15 -> Option AQuick Check:
Minimum capacity = 15 [OK]
- Choosing max weight instead of sum as answer
- Confusing days count in canShip function
- Not using Math.floor for mid calculation
function canPlace(positions: number[], distance: number, m: number): boolean {
let count = 1, lastPos = positions[0];
for (let i = 1; i < positions.length; i++) {
if (positions[i] - lastPos >= distance) {
count++;
lastPos = positions[i];
}
}
return count >= m;
}
function maxMinDistance(positions: number[], m: number): number {
positions.sort((a, b) => a - b);
let low = 0, high = positions[positions.length - 1] - positions[0];
while (low < high) {
const mid = Math.floor((low + high + 1) / 2);
if (canPlace(positions, mid, m)) low = mid;
else high = mid - 1;
}
return low;
}Solution
Step 1: Analyze canPlace function
It correctly counts placements with given minimum distance.Step 2: Check binary search logic
Mid uses upper mid to avoid infinite loop, loop condition low < high is valid, and updates low/high correctly.Final Answer:
No bug; code works correctly -> Option DQuick Check:
Code logic correct = A [OK]
- Changing loop condition incorrectly
- Removing +1 in mid causing infinite loop
- Forgetting to sort positions array
k workers, where each worker does continuous tasks. Given tasks array of times, how would you apply binary search on answer to solve this?Choose the best approach.
Solution
Step 1: Define search space for answer
Minimum max time is max single task time; maximum is sum of all tasks.Step 2: Check feasibility with mid value
Check if tasks can be divided into ≤ k continuous groups with max sum ≤ mid.Step 3: Adjust search space based on feasibility
If feasible, try smaller max time; else increase it.Final Answer:
Binary search on time range; check if tasks can be split into ≤ k groups with max sum ≤ mid. -> Option BQuick Check:
Binary search on max time with group check = D [OK]
- Sorting tasks instead of binary searching answer
- Trying to binary search on task count directly
- Ignoring continuous group constraint
Ready to prove it?
Pass the test and this pattern moves unknown
