Problem Statement
Guess Number Higher or Lower
We are playing a guessing game. I pick a secret number somewhere from 1 to n. Your job is to figure out which number I picked. You are not guessing blindly. Each time you guess, you call a helper called guess(num), and it gives you a hint back: it returns -1 if your guess is too high (the secret is lower), 1 if your guess is too low (the secret is higher), and 0 when your guess is exactly right. So every guess tells you which direction to look next.
Signals to notice
Brute force first
Try every number from 1 to n. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Binary search the range: guess the midpoint, adjust range based on feedback. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.
Trace it on n=10, pick=6
init: left=1, right=10 mid=(1+10)//2=5; guess(5)=1 (too low) -> left=6 mid=(6+10)//2=8; guess(8)=-1 (too high) -> right=7 mid=(6+7)//2=6; guess(6)=0 (match) -> return 6 answer: 6
What must stay true
Each guess eliminates half the remaining candidates. As long as that statement keeps holding, you can trust the steps built on top of it.
Shape of the loop
left, right = 1, n
while left <= right:
mid = (left + right) // 2
r = guess(mid)
if r == 0: return mid
elif r == -1: right = mid - 1 # mid too high
else: left = mid + 1 # mid too lowPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Integer overflow when calculating mid — use left + (right - left) / 2 instead of (left + right) / 2. The fix is usually to return to the meaning of each move, not just the steps themselves.