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?