Complete the code to initialize the search range for binary search on answer.
int low = 0; int high = [1];
The high value is set to a large number (1e9) to cover the maximum possible answer range.
Complete the code to calculate the middle value in binary search on answer.
int mid = low + ([1] - low) / 2;
We calculate mid as low + (high - low) / 2 to avoid overflow.
Fix the error in the condition to update the search range based on feasibility check.
if (isPossible([1])) { high = mid - 1; } else { low = mid + 1; }
The feasibility check should be done on mid, the current candidate answer.
Fill both blanks to complete the binary search loop condition and update low when answer is not possible.
while ([1] <= [2]) { int mid = low + (high - low) / 2; if (isPossible(mid)) { high = mid - 1; } else { low = mid + 1; } }
The loop continues while low is less than or equal to high.
We update low to mid + 1 when the answer is not possible.
Fill all three blanks to return the final answer after binary search on answer completes.
int binarySearchAnswer() {
int low = 0, high = 1e9;
int result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (isPossible(mid)) {
result = [1];
high = [2];
} else {
low = [3];
}
}
return result;
}
When mid is possible, we store it in result and move high to mid - 1 to find a smaller possible answer.
Otherwise, we move low to mid + 1 to search higher.