KatInterview

Binary Search with Delayed Feedback Protocol

Heaps, Sorting & SearchModel answer
HardModel answerHeaps, Sorting & Searchbinary-searchalgorithmsfeedback-systems

Last 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 returns None since 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 -1 if your previous guess was less than target
    • Returns 1 if your previous guess was greater than target
    • Returns 0 if your previous guess equals target
  • 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.