Secret Number Search with One-Call-Delayed Feedback
Learn this problemProblem statement
A secret integer is between 1 and upperBound, inclusive. A guessing service has a one-call delay: a call submits a new guess but returns the comparison for the immediately preceding call's guess.
You receive the recorded feedback array from the deterministic binary-search protocol below. Reconstruct the search and return the secret integer. The secret and the submitted guesses are not provided as inputs.
Initially, the inclusive candidate interval is [1, upperBound]. For each array entry, perform these actions in this exact order:
- Before processing this entry, submit the lower midpoint of the current interval:
low + (high - low) / 2, with integer division. - Read this entry as the service's response. The first entry is
2, meaning that no earlier guess exists. Every later entry describes the previous submitted guess:1means that guess was too low,-1means it was too high, and0means it equals the secret. - For a too-low response, remove candidates less than or equal to the previous guess. For a too-high response, remove candidates greater than or equal to the previous guess. Never put an already removed candidate back into the interval.
- If the response is
0, return the previous guess and stop. Otherwise, remember the newly submitted guess for the following entry.
The next guess is therefore submitted before the pending response is applied. Consecutive calls may submit the same midpoint, and the resulting repeated comparisons must still refer to the correct prior guess. The final entry is the first 0; it is obtained by another ordinary call, not by a separate flush operation. Its newly submitted guess does not need a response because the search has finished.
The transcript is guaranteed to be complete and consistent with this protocol for exactly one secret. You do not need to validate malformed input or contact a real service.
Function
findSecretFromDelayedFeedback(upperBound: int, feedback: int[]) → intExamples
Example 1
upperBound = 10feedback = [2,1,1,-1,-1,1,1,0]return = 7The submitted guesses are [5,5,8,8,6,6,7,7]. The third response is still about the second guess, 5, even though the newly submitted guess is 8. The last response confirms that the preceding guess, 7, is the secret.
Example 2
upperBound = 8feedback = [2,-1,-1,0]return = 2The guesses are [4,4,2,2]. Both too-high responses describe a guess of 4. The final response confirms the previous guess of 2.
Constraints
1 ≤ upperBound ≤ 100000.2 ≤ feedback.length ≤ 100.feedback[0] = 2, the final entry is0, and every intervening entry is-1or1.- The transcript follows the stated lower-midpoint protocol and is consistent with a secret in the initial interval.