Guess Number Higher or Lower — LeetCode 374 Python Solution
EasyBinary SearchInteractive
- Problem
- #374
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
We are playing the Guess Game. The game is as follows: I pick a number from 1 to n.
Example
- Input
- n = 10, pick = 6
- Output
- 6
Python solution
Python
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if num is higher than the picked number
# 1 if num is lower than the picked number
# otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
return bisect.bisect(range(1, n + 1), 0, key=lambda x: -guess(x))Complexity
| Measure | Complexity |
|---|---|
| Time | O(\log n), where n is the upper limit given in the problem |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 374. Guess Number Higher or Lower is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 374. Guess Number Higher or Lower?
- LeetCode 374. Guess Number Higher or Lower is rated Easy on LeetCode.
- What is the time complexity of LeetCode 374. Guess Number Higher or Lower?
- The Python solution on this page runs in O(\log n), where n is the upper limit given in the problem.
- What is the space complexity of LeetCode 374. Guess Number Higher or Lower?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 374. Guess Number Higher or Lower cover?
- LeetCode 374. Guess Number Higher or Lower is tagged Binary Search and Interactive on LeetCode.