C++ 0374.cpp
class Solution {
public:
int guessNumber(int n) {
int64_t pick = 1 << 30; // halfway between 1 and 2^31 - 1
int64_t step = pick >> 1;
while (true)
{
auto hint = guess(pick);
if (hint == 0)
break;
pick += step * hint;
step >>= 1;
}
return pick;
}
};
Difficulty
and has an acceptance rate of about 57% (1+ million submissions).
Typical patterns to solve this problem:
- Binary Search
- Interactive
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented Solution class implements a number-guessing routine that interacts with an external guess API. The algorithm searches for a hidden integer within the range [1, 2^31-1] by repeatedly adjusting a candidate value (pick) based on the feedback (hint) returned by guess. The core idea is a binary-search-like narrowing of the search interval, realized through bit-wise operations that avoid costly arithmetic.
Key Steps
The method guessNumber follows a deterministic sequence of actions:
-
Initial candidate and step size
int64_t pick = 1 << 30; // halfway between 1 and 2^31 - 1 int64_t step = pick >> 1;The initial
pickis set to2^30, which is the midpoint of the full search space. The accompanyingstepis half of that value, establishing the first adjustment magnitude. -
Iterative probing loop
while (true) { auto hint = guess(pick); if (hint == 0) break; pick += step * hint; step >>= 1; }Inside the infinite loop, the code queries the
guessfunction with the currentpick. The returnedhintcan be0(correct),-1(target is lower), or1(target is higher). A zero hint terminates the loop. Otherwise,pickis moved toward the target by addingstepmultiplied by the sign ofhint. After each adjustment,stepis halved using a right shift, progressively refining the search granularity. -
Result return
return pick;When the loop exits,
pickholds the exact hidden number, which is then returned to the caller.
Edge Cases Handled
The algorithm gracefully accommodates the extreme bounds of the search interval. By initializing pick to 2^30 and step to 2^29, the first adjustment can reach both the lower bound (1) and the upper bound (2^31-1) in a single step if the hidden number lies at either extreme. The use of a signed hint multiplier (-1 or 1) ensures that the direction of movement is correctly applied regardless of whether the target is above or below the current pick. The loop continues until step becomes zero, at which point the only remaining possible value is the correct one, guaranteeing termination even when the hidden number is adjacent to the initial midpoint.
Performance Optimizations
The implementation leverages several low-level techniques to maximize efficiency:
- Bit-wise initialization: Setting
pickwith1 << 30and derivingstepviapick >> 1avoids multiplication or division, yielding faster compile-time constants. - Shift-based step reduction: Halving
stepwithstep >>= 1is a constant-time operation that replaces arithmetic division, reducing CPU cycles per iteration. - Multiplication by
hint: The expressionstep * hintuses the sign ofhintto either add or subtractstepwithout branching, allowing the compiler to generate streamlined arithmetic instructions. - 64-bit arithmetic: Declaring
pickandstepasint64_tprevents overflow when intermediate values exceed the 32-bit range, eliminating the need for additional checks and keeping the loop tight. - Early exit: The loop terminates immediately upon receiving a zero hint, avoiding unnecessary iterations once the target is found.
Collectively, these choices produce a compact, high-throughput search routine that converges on the hidden number in a logarithmic number of steps while maintaining minimal overhead per iteration.
ELI5 - Simplified Explanation
Imagine a giant game of find the hidden number where a computer has picked a mystery digit and you need to guess what it is. The game is helpful because it tells you if your guess is too high, too low, or exactly right. This code acts like a very smart player that plays the game using a special strategy.
It starts by picking a number right in the middle of all the possible choices. After it makes a guess, the game gives a little hint. If the hint tells the code that the guess was too high, it knows it needs to choose a smaller number next. If the hint says the guess was too low, it tries a bigger number.
The code uses a clever trick where it makes the jumps smaller each time. It starts by taking a huge leap to narrow down the playing field, and with every step, it cuts the size of that leap in half. By doing this over and over, it zooms in on the secret number very quickly. It keeps repeating this motion until the hint says zero, which is the signal that the secret number has been found.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | C# | Python | Go | Rust | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| fartem | Ruby | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| fartem | Ruby | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 278: First Bad Version
- problem 375: Guess Number Higher or Lower II
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality