This problem looks busy at first, but the accepted solution is built around one steady invariant. For 374. Guess Number Higher or Lower, the solution in this repository is mainly a two pointers solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: two pointers, sliding window.
The notes already sitting in the source point us in the right direction:
- Forward declaration of guess API.
- @param num, your guess
- @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are guess, guessNumber.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Guess Number Higher or Lower.
02//Memory Usage: 7.3 MB, less than 100.00% of C++ online submissions for Guess Number Higher or Lower.
03
04// Forward declaration of guess API.
05// @param num, your guess
06// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
07int guess(int num);
08
09class Solution {
10public:
11 int guessNumber(int n) {
12 int left = 1, right = n, cur = left+(right-left)/2;
13
14 while(true){
15 switch(guess(cur)){
16 case -1:
17 right = cur-1;
18 cur = left+(right-left)/2;
19 break;
20 case 1:
21 left = cur+1;
22 cur = left+(right-left)/2;
23 break;
24 case 0:
25 return cur;
26 }
27 }
28 return 0;
29 }
30};
Cost