Binary Search with Delayed Feedback Protocol
Heaps, Sorting & SearchModel answerLast updated
Find a hidden number using binary search when each query returns the result of your previous guess instead of your current one.
Problem Description
You're implementing a search algorithm where feedback arrives one step behind your queries. You need to locate a hidden integer target within the range [1, n] by interacting with an oracle that has unusual timing behavior.
The oracle interface oracle.guess(x: int) -> int | None works as follows:
- Initial query: Your first call to
oracle.guess(x)records your guess but returnsNonesince there's no prior guess to evaluate. - Subsequent queries: Each call after the first records your new guess and returns the evaluation of your previous guess:
- Returns
-1if your previous guess was less thantarget - Returns
1if your previous guess was greater thantarget - Returns
0if your previous guess equalstarget
- Returns
- Reading final results: To learn the outcome of your most recent guess, you must issue another guess (which can be any valid value in
[1, n]).
Your task is to implement find_target(n: int, oracle: DelayedOracle) -> int that locates the target efficiently.
Interface
class DelayedOracle:
def guess(self, x: int) -> int | None:
...
def find_target(n: int, oracle: DelayedOracle) -> int:
pass
Requirements
- Your solution must use
O(log n)oracle calls - The constant factor should be reasonable (a small multiple of
log₂ n) - Handle all edge cases including
n = 1
Examples
Example 1:
n = 10, target = 7
Possible execution:
1. oracle.guess(5) -> None # First guess recorded, no feedback yet
2. oracle.guess(5) -> -1 # Learn that 5 < 7, register second guess of 5
3. oracle.guess(8) -> -1 # Learn that 5 < 7 (again), register guess of 8
4. oracle.guess(8) -> 1 # Learn that 8 > 7, register second guess of 8
5. oracle.guess(7) -> 1 # Learn that 8 > 7 (again), register guess of 7
6. oracle.guess(7) -> 0 # Learn that 7 == 7, found!
Returns: 7
Example 2:
n = 1, target = 1
Execution:
1. oracle.guess(1) -> None # Record guess
2. oracle.guess(1) -> 0 # Confirm guess was correct
Returns: 1
Considerations
- The feedback lag means you cannot immediately act on your latest guess
- When narrowing your search space, you must account for which guess the feedback actually describes
- Consider how to verify your final answer when the search interval collapses to one candidate
Hints
Hint 1
The simplest approach is to make each meaningful guess twice: once to record it, and once more to retrieve its feedback.
Hint 2
Track which guess each returned value corresponds to—the kth call gives you feedback about guess k-1, not guess k.
Hint 3
When your search interval reaches a single value, you still need to query the oracle to confirm it's correct.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
The core challenge is synchronizing your decision-making with delayed feedback. When you submit a guess, you cannot branch on its result until your next oracle interaction. The cleanest solution uses a double-call pattern: every meaningful guess is submitted twice.
Strategy
For each binary search iteration:
- Submit your midpoint guess — call
oracle.guess(mid). The returned value reflects an old guess we've already processed, so we discard it (on the first iteration, it'sNone). - Immediately submit the same guess again — call
oracle.guess(mid)a second time. This returns the evaluation of the firstguess(mid)call, which is exactly what we need to decide how to narrow our search. - Update the search interval using standard binary search logic:
- If the result is
-1:mid < target, so search[mid + 1, hi] - If the result is
1:mid > target, so search[lo, mid - 1] - If the result is
0: we've found the target, returnmid
- If the result is
Why This Works
Correctness invariant: Before each iteration, the target is guaranteed to be in [lo, hi], and any pending guess result is one we don't need.
- The first
guess(mid)in each iteration returns feedback about the previous iteration's secondguess(mid)call—but we already acted on that feedback, so we safely ignore it. - The second
guess(mid)gives us the fresh evaluation we need. - Submitting
midtwice is safe becausemidis always within the valid range[1, n], and if it happens to be correct, the second call tells us immediately.
Termination: The interval shrinks by at least half each iteration. When lo == hi, the only remaining candidate must be the target, and our confirmation query will return 0.
Complexity Analysis
- Oracle calls: Each iteration requires exactly 2 calls. With at most
⌈log₂ n⌉ + 1iterations, the total is approximately2·log₂ n + 2calls. Forn = 10⁹, this is around 60 calls. - Time complexity:
O(log n) - Space complexity:
O(1)
Edge Cases
- Single element (
n = 1): Requires one query to register the guess and one to read its result—exactly 2 calls total. - Target at boundaries: When the target is
1orn, the algorithm narrows to that endpoint correctly. - First call returns
None: Must be handled explicitly; it's not a comparison result. - Integer overflow prevention: Use
mid = lo + (hi - lo) // 2rather than(lo + hi) // 2(though Python handles large integers automatically).
Implementation
class DelayedOracle:
def guess(self, x: int) -> int | None:
...
def find_target(n: int, oracle: DelayedOracle) -> int:
lo, hi = 1, n
while lo <= hi:
mid = lo + (hi - lo) // 2
# Submit the guess; return value is stale feedback we don't need
oracle.guess(mid)
# Submit again to retrieve feedback for the guess we just made
result = oracle.guess(mid)
if result == 0:
return mid
elif result == -1:
# Previous guess was too low
lo = mid + 1
else: # result == 1
# Previous guess was too high
hi = mid - 1
# Should never reach here if target is guaranteed to be in [1, n]
raise ValueError("Target not found in valid range")
Common Mistakes
- Acting on stale feedback: Reading the first return value in each iteration and treating it as feedback for the current
midproduces incorrect search intervals. - Off-by-one in the final step: Forgetting that even when
lo == hi, you still need to query the oracle to verify. - Not handling
Noneon first call: TreatingNoneas a comparison result causes type errors or logic bugs. - Inefficient flushing: Some candidates create complex state machines to track pending guesses. The double-call pattern is simpler and provably correct.
Advanced Considerations
The double-call approach uses a constant factor of C = 2. The theoretical optimum for one-step delay is C ≈ 1.44, achieved through Fibonacci search variants that pipeline guesses more aggressively—continuing to query while earlier results are in flight. The tradeoff is significantly more complex bookkeeping. For interview purposes, the double-call strategy demonstrates understanding of the feedback lag and is entirely sufficient.
If the oracle could only return < or ≥ (no equality signal), you'd need to run until lo == hi and return that value without confirmation, making the in-range guarantee essential. With network latency and multiple in-flight request slots, you'd optimize for round trips rather than total queries, potentially using k+1-ary search or speculative tree exploration.