Binary Search on Answer Technique in DSA Go - Time & Space Complexity
We want to understand how the time needed grows when using the binary search on answer method.
This helps us know how fast the solution finds the correct answer by narrowing down possibilities.
Analyze the time complexity of the following code snippet.
func binarySearchOnAnswer(low, high int, condition func(int) bool) int {
for low <= high {
mid := (low + high) / 2
if condition(mid) {
high = mid - 1
} else {
low = mid + 1
}
}
return low
}
This code tries to find the smallest value that satisfies a condition by repeatedly checking the middle of a range.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that halves the search range each time.
- How many times: The loop runs about log base 2 of the range size times.
Each step cuts the search space in half, so the number of steps grows slowly as input size grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 checks |
| 100 | About 7 checks |
| 1000 | About 10 checks |
Pattern observation: Doubling the input size adds only one extra step.
Time Complexity: O(log n)
This means the time needed grows slowly, increasing by one step each time the input doubles.
[X] Wrong: "The loop runs n times because it looks like a while loop over a range."
[OK] Correct: Each loop cuts the range in half, so it runs much fewer times than n, about log n times.
Understanding this technique shows you can solve problems efficiently by smartly narrowing down answers, a valuable skill in many coding challenges.
"What if the condition function takes linear time to check? How would the overall time complexity change?"
Practice
Binary Search on Answer technique?Solution
Step 1: Understand the technique concept
Binary Search on Answer guesses a possible answer and checks if it meets the problem's conditions.Step 2: Adjust guess based on check
If the guess is too high or too low, we adjust it using binary search until the best answer is found.Final Answer:
We guess an answer and check if it satisfies the problem, then adjust the guess using binary search. -> Option AQuick Check:
Guess and check with binary search = D [OK]
- Confusing with normal binary search on arrays
- Thinking it always requires sorting input
- Assuming recursion is mandatory
Solution
Step 1: Identify Go loop syntax for binary search
Go usesforloops for iteration;for low <= high { ... }is correct for binary search.Step 2: Check other options for syntax errors
whileis not valid in Go;for i := low; i < high; i++is a counting loop, not binary search;ifis conditional, not loop.Final Answer:
for low <= high { mid := (low + high) / 2 } -> Option CQuick Check:
Go binary search loop uses for low <= high [OK]
- Using while loop (not valid in Go)
- Using for with increment instead of condition
- Using if instead of loop
low, high := 1, 10
var ans int
for low <= high {
mid := (low + high) / 2
if mid*mid >= 10 {
ans = mid
high = mid - 1
} else {
low = mid + 1
}
}
fmt.Println(ans)
What will be printed?Solution
Step 1: Trace binary search for x where x*x >= 10
Check mid values: - mid=5: 25 >=10 true, ans=5, high=4 - mid=2: 4 >=10 false, low=3 - mid=3: 9 >=10 false, low=4 - mid=4: 16 >=10 true, ans=4, high=3 Loop ends, ans=4Step 2: Find minimum x satisfying condition
Minimum x with x*x >=10 is 4, so ans=4.Final Answer:
4 -> Option BQuick Check:
Minimum x with x²≥10 is 4 [OK]
- Choosing mid incorrectly (integer division errors)
- Not updating ans when condition is true
- Confusing >= with >
func maxRopeLength(ropes []int, k int) int {
low, high := 1, 0
for _, r := range ropes {
if r > high {
high = r
}
}
ans := 0
for low < high {
mid := (low + high) / 2
count := 0
for _, r := range ropes {
count += r / mid
}
if count >= k {
ans = mid
low = mid + 1
} else {
high = mid - 1
}
}
return ans
}Solution
Step 1: Analyze binary search loop condition
The loop usesfor low < high, which misses the case when low == high, possibly skipping the final answer.Step 2: Correct loop condition for binary search
Changing tofor low <= highensures all candidates are checked, including when low equals high.Final Answer:
The loop condition should be low <= high, not low < high. -> Option AQuick Check:
Binary search loops use low <= high [OK]
- Using low < high and missing final check
- Confusing integer and float division here
- Initializing ans incorrectly
Solution
Step 1: Define search space for answer
The minimum maximum workload must be at least the largest single task time (low) and at most the sum of all tasks (high).Step 2: Check feasibility in binary search
For each mid in [low, high], check if tasks can be assigned to m workers without exceeding mid workload per worker.Step 3: Adjust search based on feasibility
If feasible, try smaller max workload (high = mid - 1), else increase (low = mid + 1).Final Answer:
Set low as max task time, high as sum of all tasks; binary search on this range checking feasibility of workload limit. -> Option DQuick Check:
Search between max task and sum, check feasibility [OK]
- Setting low to 0 ignoring max task time
- Searching on wrong variable like number of workers
- Not checking feasibility properly
Ready to prove it?
Pass the test and this pattern moves unknown
